<?php
/**
* Microorganisms
* Manage all microorganisms in the system
* 
* @package Microorganism
* @author Argem Gerald R. Flores <argemgrflores@gmail.com>
* @version 1.0
*/
class Microorganism {
	/**
	* @var mixed Mysql connection
	*/
	var $mysqli = null;
	/**
	* @var array User credentials (id, email, type)
	*/
	var $user = null;
	/**
	* @var array Notifications
	*/
	var $notif = array();
	/**
	* @var string Area of concentration
	*/
	var $area = 'micro';
	/**
	* @var string Database table to be used
	*/
	var $table = 'Microorganisms';
	/**
	* @var string Parent ID
	*/
	var $pid = 'ID';
	/**
	* @var string Child ID
	*/
	var $cid = null;
	
	/**
	* Microorganism constructor
	* Initializes Microorganism variables for intended request
	* 
	* @param string $area Area of concentration
	* @param resource $mysqli Current mysql connection
	* @param resource $user User credentials (id, email, type)
	*/
	function __construct($area, $mysqli, $user) {
		# require all necessary classes
		require_once "class/setting.php";
		require_once "class/fpdf.php";
		require_once "class/file.php";
		require_once "class/resource.php";
		require_once "class/location.php";
		require_once "class/image.php";
		require_once "class/document.php";
		require_once "class/section.php";
		require_once "class/project.php";
		require_once "class/tool.php";
		
		$this->mysqli = $mysqli;
		$this->user = $user;
		$this->area = $area;
		
		switch($area) {
			case 'proj':
				$this->table = 'ProjMicros';
				$this->pid = 'PID';
				$this->cid = 'CID';
			break;
			
			case 'img':
				$this->table = 'MicroImgs';
				$this->pid = 'CID';
				$this->cid = 'PID';
			break;
			
			case 'doc':
				$this->table = 'MicroDocs';
				$this->pid = 'CID';
				$this->cid = 'PID';
			break;
			
			case 'loc':
				$this->table = 'MicroLocs';
				$this->pid = 'CID';
				$this->cid = 'PID';
			break;
			
			default:
				$this->taxatb = array (
					'Kingdoms', 'Phyla', 'Classes', 'Orders', 'Families', 'Genera', 'Species',
					'kng'=>'Kingdoms', 'phy'=>'Phyla', 'cls'=>'Classes', 'ord'=>'Orders', 'fam'=>'Families', 'gen'=>'Genera', 'spc'=>'Species',
					'kingdom'=>'Kingdoms', 'phylum'=>'Phyla', 'class'=>'Classes', 'order'=>'Orders', 'family'=>'Families', 'genus'=>'Genera', 'species'=>'Species'
				);
				$this->taxaid = array (
					'KngID', 'PhyID', 'ClsID', 'OrdID', 'FamID', 'GenID', 'SpcID',
					'kng'=>'KngID', 'phy'=>'PhyID', 'cls'=>'ClsID', 'ord'=>'OrdID', 'fam'=>'FamID', 'gen'=>'GenID', 'spc'=>'SpcID',
					'kingdom'=>'KngID', 'phylum'=>'PhyID', 'class'=>'ClsID', 'order'=>'OrdID', 'family'=>'FamID', 'genus'=>'GenID', 'species'=>'SpcID'
				);
				$this->taxalabel = array(
					'Kingdom', 'Phylum', 'Class', 'Order', 'Family', 'Genus', 'Species',
					'kng'=>'Kingdom', 'phy'=>'Phylum', 'cls'=>'Class', 'ord'=>'Order', 'fam'=>'Family', 'gen'=>'Genus', 'spc'=>'Species',
					'kingdom'=>'Kingdom', 'phylum'=>'Phylum', 'class'=>'Class', 'order'=>'Order', 'family'=>'Family', 'genus'=>'Genus', 'species'=>'Species'
				);
				$this->ranks = array('kingdom', 'phylum', 'class', 'order', 'family', 'genus', 'species');
			break;
		}
	} # function __construct
	
	/**
	* Search microorganism
	* Searches for a microorganism based on
	* query string, optional paramaters as constraints,
	* start and end line of result in a mysql resource
	* 
	* @access public
	* @param string $query Keyword/s to look for in the database
	* @param array $opts Contains constraints in search (category, order, author, etc.)
	* @param integer $start Beginning line of searched keyword in mysql resource
	* @param integer $limit End of returned mysql resource as a result of search
	* 
	* @return array Mixed result from mysql query and size of returned rows
	*/
	public function search($query, $opts, $start, $limit) {
		$query = is_array($query) ? $query : Tool::trimout($query);
		$selSize = "SELECT FOUND_ROWS()";
		
		# Switch to area of conscentration
		switch($this->area) {
			# Guess taxonomic position
			case 'taxong':
				$sel = "SELECT SQL_CALC_FOUND_ROWS * FROM {$this->taxatb[$opts['i']]} WHERE Name LIKE '%{$query}%' OR Code LIKE '%{$query}%' ";
			break;
			
			# Get taxonomy
			case 'taxon':
				$result = array();
				$sel = "SELECT * FROM {$this->taxatb[$opts['rnk']]} WHERE ID='{$query}' OR Name LIKE '%{$query}%' OR Code='{$query}'";
				
				# Found taxonomy
				if(($res = $this->mysqli->query($sel)) and !empty($res->num_rows)) {
					$result[$opts['rnk']] = $res;
					$taxon = $res->fetch_object();
					$keys = $this->taxaid;
					
					# List all taxons
					for($i=0; $i<$opts['rnk']; $i++) {
						$sel = "SELECT * FROM {$this->taxatb[$i]} WHERE ID='{$taxon->$keys[$i]}' OR Code='{$taxon->$keys[$i]}'";
						if($res = $this->mysqli->query($sel) and !empty($res->num_rows)) {
							$result[$i] = $res;
						}
					}
					
					# Get all higher taxons
					if($opts['rnk']+1 < 7) {
						$sel = "SELECT * FROM {$this->taxatb[$opts['rnk']+1]} WHERE {$keys[$opts['rnk']]}='{$taxon->ID}' OR Code='{$taxon->ID}'";
						
						if(($res = $this->mysqli->query($sel)) and !empty($res->num_rows)) {
							$result[$opts['rnk']+1] = $res;
						}
					}
				}
				
				# Return resulting array
				return $result;
			break;
			
			# Hosts
			case 'host':
				$sel = "SELECT SQL_CALC_FOUND_ROWS * FROM Hosts AS T1 INNER JOIN HostComnames AS T2 WHERE T1.Name LIKE '%{$query}%' OR T1.Code LIKE '%{$query}%' OR T2.Name LIKE '%{$query}%'";
			break;
			
			# Other categories
			default:
				# Search microorganism via its ID
				if($opts["c"]=="id" or $opts["c"]=="view") {
					$query = empty($opts['id']) ? $query : $opts['id'];
					
					$sel = "
						SELECT SQL_CALC_FOUND_ROWS DISTINCT T1.* FROM Microorganisms AS T1 WHERE (T1.ID='{$query}' OR T1.Code='{$query}') ".(in_array($this->user['type'], array('ADMIN','PRIME')) ? '' : "AND T1.Remove='0'")."
							AND ('{$this->user['type']}'='PRIME' OR T1.Visib='PUB' OR (T1.Visib='PRV' AND (T1.CrtBy='{$this->user['id']}'
							OR (SELECT COUNT(*) FROM MicroCoeds AS T2 WHERE T2.PID='{$query}' AND T2.CID='{$this->user['id']}') > 0)))
						ORDER BY T1.Name
					";
				}
				else {
					$cond = "";
					
					# Switch category associated with microorgainsm
					switch($opts["c"]) {
						# Synonyms
						case 'syno':
							$categ = "
								INNER JOIN MicroSynos AS T3 ON T1.ID=T3.CID WHERE T1.Name LIKE '%{$query}%'
							";
						break;
						
						# Common names
						case 'comn':
							$categ = "
								INNER JOIN Comnames AS T3 INNER JOIN MicroComns AS T4 ON T1.ID=T4.PID AND T3.ID=T4.CID WHERE T3.Name LIKE '%{$query}%'
							";
						break;
						
						# Taxonomic position
						case 'taxon':
							$categ = "
								INNER JOIN {$this->taxatb[$opts['rnk']]} AS T3 ON T1.{$this->taxaid[$opts['rnk']]}=T3.ID WHERE T3.Name LIKE '%{$query}%' OR T3.Code LIKE '%{$query}%'
							";
						break;
						
						# Hosts
						case 'host':
							$categ = "
								INNER JOIN Hosts AS T3 INNER JOIN HostComnames AS T4 INNER JOIN MicroHosts AS T5 INNER JOIN HostComns AS T6
								ON T1.ID=T5.PID AND (T3.ID=T5.CID OR (T3.ID=T6.PID AND T4.ID=T6.CID)) WHERE T3.Name LIKE '%{$query}%' OR T4.Name LIKE '%{$query}%'
							";
						break;
						
						# Projects
						case "proj":
							$categ = "
								INNER JOIN ProjMicros AS T3 INNER JOIN Projects AS T4
									ON T1.ID=T3.CID AND T3.PID=T4.ID
								WHERE T4.Title LIKE '%{$query}%' OR T4.Abstr LIKE '%{$query}%'
							";
						break;
						
						# Locations
						case "loc":
							$categ = "
								INNER JOIN MicroLocs AS T3 INNER JOIN Locations AS T4
									ON T1.ID=T3.PID AND T3.CID=T4.ID
								WHERE T4.Name LIKE '%{$query}%' OR T4.Notes LIKE '%{$query}%'
							";
						break;
						
						# Multiple ids
						case "multi-id":
							$categ = "WHERE T1.ID IN ('".implode("','", $query)."')";
						break;
						
						# Exact Scientific name
						case 'exact':
							$categ = "WHERE (T1.Name='{$query}') ";
						break;
						
						# All microorganisms
						case 'all':
							$categ = "WHERE T1.Name LIKE '%{$query}%' ";
						break;
						
						# By authors
						case 'auth':
							$categ = "WHERE T1.Authors LIKE '%{$query}%' ";
						break;
						
						# Scientific name
						case "name":
							$categ = "WHERE T1.Name LIKE '%{$query}%' ";
						break;
					}
					
					# Order category and ordering
					$opts["ob"] = isset($opts["ob"]) ? $opts['ob'] : "Name";
					$opts["oa"] = isset($opts["oa"]) ? $opts["oa"] : "ASC";
					
					# Included words/phrase
					if(!empty($opts["i"])) {
						$cond .= "(T1.Name LIKE '%{$opts["i"]}%') AND ";
					}
					
					# Excluded words/phrase
					if(!empty($opts["e"])) {
						$arrQuery = explode(", ", $opts["e"]);
						$cond .= "(T1.Name NOT LIKE '%".implode("%' AND T1.Name NOT LIKE '%", $arrQuery)."%') AND ";
					}
					
					# Creator
					if(!empty($opts["cb"])) {
						if(empty($opts['cbi'])) {
							$name = explode(", ", $opts["cb"]);
							
							# Last name, First name, Mid name
							if(count($name)==3) {
								list($lname, $fname, $mi) = $name;
								$cond .= "(T1.CrtBy IN (SELECT ID FROM Accounts WHERE Lname='".Tool::trimout($lname)."'AND Fname='".Tool::trimout($fname)."') AND ";
							}
							# Email
							elseif(strrpos($opts['cb'], '@') > 1) {
								$cond .= "(T1.CrtBy IN (SELECT ID FROM Accounts WHERE Email='{$opts['cb']}')) AND ";
							}
							# Other
							else {
								$cond .= "(T1.CrtBy='%{$query}%') AND ";
							}
						}
						else {
							# Account ID
							$cond .= "(T1.CrtBy='{$opts['cbi']}') AND ";
						}
					}
					
					# Creation date
					if(!empty($opts['co']['s'])) {
						# Date range
						if(!empty($opts["co"]["e"])) {
							$cond .= " (T1.CrtOn BETWEEN '".Tool::trimout($opts["co"]["s"])."' AND '".Tool::trimout($opts["co"]["e"])."') AND ";
						}
						# Exact date
						else {
							$cond .= " (T1.CrtOn='".Tool::trimout($opts["co"]["s"])."') AND ";
						}
					}
					
					# Taxon it belongs to
					if(!empty($opts['taxon'])) {
						$res = $this->mysqli->query("SELECT * FROM {$this->taxatb[$opts['taxon']]} WHERE ID='{$query}' OR Name='{$query}' OR Code='{$query}'");
						
						# Searched and found taxon
						if(!empty($res->num_rows)) {
							$obj = $res->fetch_object();
							$cond .= "({$this->taxaid[$opts['taxon']]}='{$obj->ID}') AND ";
							# Set label
							$_REQUEST['htitle'] = $this->taxalabel[$opts['taxon']].': '.$obj->Name.' ('.$obj->Code.')';
						}
					}
					# Any other constraint
					elseif(empty($opts["c"])) {
						$cond .= "(T1.Name LIKE '%{$query}%' OR T1.Code='{$query}' OR T1.Notes LIKE '%{$query}%') AND ";
					}
					
					# Removed items
					$cond .= (in_array($this->user['type'], array('ADMIN','PRIME')) and $opts['c']=='remove') ? " T1.Remove='1' AND " : " T1.Remove='0' AND ";
					
					# Limit of returned rows
					$range = (isset($start) and !empty($limit)) ? "LIMIT {$start}, {$limit}" : '';
					
					if(empty($categ)) {
						$cond = "
							WHERE {$cond} ".(empty($opts['view']) ? '' : "Pref='1' AND")." (T1.Visib='PUB' OR ('{$this->user['type']}'='PRIME')
								OR (T1.Visib='PRV' AND (T1.CrtBy='{$this->user['id']}'
								OR (SELECT COUNT(T2.CID) FROM MicroCoeds AS T2 WHERE T2.PID=T1.ID AND T2.CID='{$this->user['id']}') > 0)))
						";
					}
					else {
						$cond = "
							{$categ} AND {$cond} (T1.Visib='PUB' OR ('{$this->user['type']}'='PRIME')
								OR (T1.Visib='PRV' AND (T1.CrtBy='{$this->user['id']}'
								OR (SELECT COUNT(T2.CID) FROM MicroCoeds AS T2 WHERE T2.PID=T1.ID AND T2.CID='{$this->user['id']}') > 0)))
						";
					}
					
					# Final query string
					$sel = "
						SELECT SQL_CALC_FOUND_ROWS DISTINCT T1.* FROM Microorganisms AS T1 {$cond} ORDER BY T1.{$opts["ob"]} {$opts["oa"]} {$range}
					";
				}
			break;
		}
		
		# Search microorganism in database
		$res = $this->mysqli->query($sel);
		$size = $this->mysqli->query($selSize);
		$size = $size->fetch_row();
		
		# Return results
		return array($res, $size[0]);
	} # function search
	
	/**
	* Create microorganism
	* Create a new microorganism entry on the system
	* 
	* @access public
	* @param mixed $name Scientific name of microorganism (Genus species)
	* @param mixed $code Code
	* @param mixed $author Scientific authors
	* @param mixed $pref Preferred name, esp. if a synonym
	* @param mixed $taxon Taxonomic position
	* @param mixed $synos Synonyms
	* @param mixed $comns Common names
	* @param mixed $hosts Host species
	* @param mixed $locs Distribution
	* @param mixed $notes Additional information
	* @param mixed $files Images and documents attached
	* @param string $coeds Coeditors
	* @param string $categ Category (Advanced, Basic)
	* @param string $visib Visibility (Private, Public)
	* 
	* @return mixed id on success, false on failure
	*/
	public function create(
		$name, $code, $author, $pref, $prefID, $taxon, $synos, $comns, $hosts, $locs,
		$notes, $ref, $imgs, $docs, $files, $coeds, $categ, $visib
	) {
		# Generate a micro ID
		$id = Tool::generateID('micro');
		
		# Prepare values for mysql query
		$name = Tool::mysqlEscStr($name);
		$pref = empty($pref) ? "'0'" : "'".$pref."'";
		$code = empty($code) ? 'NULL' : "'".$code."'";
		$author = empty($author) ? 'NULL' : "'".Tool::mysqlEscStr($author)."'";
		$notes = empty($notes) ? 'NULL' : "'".Tool::mysqlEscStr($notes)."'";
		$ref = empty($ref) ? 'NULL' : "'".Tool::mysqlEscStr($ref)."'";
		
		# Prepare preferred id and taxon id
		$prefID = $this->doPrefMicro($name, $prefID);
		$taxonid = $this->doTaxonMicro($taxon);
		
		# Set settings
		$coeds = empty($coeds['val']) ? '0' : count($coeds['val']);
		$userid = $this->user['id'];
		$date = date('Y-m-d H:i:s:ms');
		
		# Insert query string
		$ins = "
			INSERT INTO Microorganisms VALUES (
				'$id', $pref, $prefID, '$categ', '$visib',
				'$name', $code, $author, $notes, $ref, $taxonid,
				NULL, $coeds, NULL, NULL, 0, NULL, NULL, 0,
				'$userid', '$date', '0'
			)
		";
		
		# Perform insert in mysql
		if($this->mysqli->query($ins)) {
			# Synonyms (non-empty)
			if(!empty($synos['name'])) {
				$this->appendSynos($id, $synos);
			}
			
			# Common names (non-empty)
			if(!empty($comns['name'])) {
				$this->appendComn($id, $comns);
			}
			
			# Hosts (non-empty)
			if(!empty($hosts['name'])) {
				$this->appendHost($id, $hosts);
			}
			
			# Locations (non-empty)
			if(!empty($locs['val']) or !empty($locs['coord'])) {
				$loc = new Location('micro', $this->mysqli, $this->user);
				$loc->append($locs, $id, array('categ'=>$categ, 'visib'=>$visib));
			}
			
			# Files (non-empty)
			if(!empty($files['temp']['name'])) {
				$file = new File('micro', $this->mysqli, $this->user);
				$file->append($files['temp'], $id, $categ, $visib);
			}
			
			if(!empty($files['path']['name'])) {
				//to-do
			}
			
			# Coeditors (non-empty)
			if(!empty($coeds['val'])) {
				$coed = new Editor('micro', $this->mysqli, $this->user);
				$coed->append($coeds, $id, false);
			}
		}
		else {
			$this->notif[] = "<li>Cannot create microorganism: <b>{$name}</b></li>";
		}
		
		if(!empty($this->notif)) {
			//echo '<pre>', var_dump($this->notif), '</pre>';
			return false;
		}
		
		# Successfully added a new microorganism
		return $id;
	} # function create
	
	/**
	* Update microorganism
	* Update an existing microorganism
	* 
	* @access public
	* @param string $id ID of Microorganism
	* @param string $name Scientific name
	* @param mixed $code Code
	* @param mixed $authors Scientific authors
	* @param mixed $pref Preferred ID
	* @param mixed $taxon Taxonomic position
	* @param mixed $synos Synonyms
	* @param mixed $comns Common names
	* @param mixed $hosts Hosts
	* @param mixed $notes Additional information
	* @param mixed $pic Primary photo
	* @param mixed $imgs Images to be appended
	* @param mixed $docs Documents to be appended
	* @param mixed $locs Locations to be appended
	* @param mixed $rsrc Resources to be appended
	* @param mixed $files Images and documents
	* @param mixed $coeds Coeditors
	* @param mixed $categ Category
	* @param string $visib Visibility
	* @param string $rsynos Synonyms to be removed
	* @param mixed $rcomns Common names to be removed
	* @param mixed $rhosts Hosts to be removed
	* @param mixed $rimgs Images to be removed
	* @param mixed $rmimgs Marks to be removed
	* @param mixed $rdocs Documents to be removed
	* @param mixed $rlocs Locations to be removed
	* @param mixed $rrsrcs Resources to be removed
	* @param mixed $rcoed Coeditors to be removed
	* 
	* @return boolean true on successful update, false on failure
	*/
	public function update(
		$id, $name, $code, $authors, $pref, $prefID, $taxon, $synos, $comns, $hosts, $notes, $ref, $pic,
		$imgs, $docs, $locs, $rsrcs, $files, $coeds, $categ, $visib, $rsynos, $rcomns, $rhosts, $rimgs, $rmimgs, $rdocs, $rlocs, $rrsrcs, $rcoeds
	) {
		# Process preferred name/id
		if(!empty($prefID['id'])) {
			# Set preferred ID if given in param
			$prefID['id'] = "'".$prefID['id']."'";
		}
		# Search microorganism for preferred name
		# if preferred name is not empty and scientific name is not equal to preferred name
		elseif(!empty($prefID['val']) and $name!=$prefID['val']) {
			# Query string to find microorganism
			$sel = "
				SELECT T1.ID FROM Microorganisms AS T1 INNER JOIN MicroSynos AS T3
					ON T1.ID=T3.PID AND T2.ID=T3.CID WHERE T1.Name='{$prefID['val']}' OR T1.Name='{$name}'
					OR T2.Name='{$prefID['val']}' OR T2.Name='{$name}'
			";
			
			# Find microorganism matching the preferred name value
			$res = $this->mysqli->query($sel);
			
			# Microorganism is found
			if($res and $res->num_rows) {
				# Set found microorganism's ID as preferred microorganism's ID
				$pmicro = $res->fetch_object();
				$prefID['id'] = "'".$pmicro->ID."'";
			}
			else {
				# Microorganism is not found
				$prefID['id'] = 'NULL';
			}
		}
		else {
			# Preferred value or ID are both empty
			$prefID['id'] = 'NULL';
		}
		
		# Input taxonomic position is empty
		if(empty($taxon)) {
			$taxonid = "KngID=NULL, PhyID=NULL, ClsID=NULL, OrdID=NULL, FamID=NULL, GenID=NULL, SpcID=NULL,";
		}
		# Find all taxonomic ranks matching the input values
		else {
			$ranks = array('kingdom', 'phylum', 'class', 'order', 'family', 'genus', 'species');
			$taxid = array('KngID', 'PhyID', 'ClsID', 'OrdID', 'FamID', 'GenID', 'SpcID');
			$taxonid = "";
			
			# Iterate through each input ranks to find rank in database
			foreach($ranks as $i => $rank) {
				# Empty taxon value at this rank
				if(empty($taxon[$rank]['name'])) {
					# Set as NULL for this rank
					$taxonid .= "{$taxid[$i]}=NULL, ";
				} # Find Taxonomic rank
				else {
					# Empty taxonomic rank id is provided
					if(empty($taxon[$rank]['id'])) {
						# Query string in selecting rank matching rank's name
						$sel = "SELECT * FROM {$this->taxatb[$i]} WHERE Name='{$taxon[$rank]['name']}'";
						
						# Select ranks from database
						$restax = $this->mysqli->query($sel);
						
						# Rank is found
						if(!empty($restax->num_rows)) {
							# Set found rank's ID as input for updating rank ID of microorganism
							$objtax = $restax->fetch_object();
							$taxon[$rank]['id'] = $objtax->ID;
						}
						# Rank is not found, thus it must be created
						else {
							# Generate an ID for that taxonomic rank
							$taxon[$rank]['id'] = Tool::generateID('taxon');
							# For subrank conditions
							$subtax = "";
							
							# Iterate through each rank from highest to lowest rank
							for($j=0; $j<$i; $j++) {
								# Check if id is empty that rank
								# If empty, set as NULL; else, set as rank ID
								$subtax .= empty($taxon[$ranks[$j]]['id']) ? 'NULL, ' : " '{$taxon[$ranks[$j]]['id']}', ";
							}
							
							# Query string to insert that rank into database
							# TaxaTB with offset at rank is the database table of rank to be inserted
							$instax = "
								INSERT INTO {$this->taxatb[$rank]} VALUES (
									'{$taxon[$rank]['id']}', '{$taxon[$rank]['name']}', '{$taxon[$rank]['code']}', {$subtax} '{$this->user['id']}', '".date('Y-m-d H:i:s:ms')."'
								)
							";
							
							# Do taxon insertion to database
							$res = $this->mysqli->query($instax);
							
							# An error occurred while inserting rank
							if(!$res) {
								$this->notif[] = 'ERROR: Error inserting rank';
							}
						}
					}
					
					# Include taxon id to taxon value string for update
					$taxonid .=  "{$taxid[$i]}='{$taxon[$rank]['id']}', ";
				}
			}
		}
		
		# Prepare all values for mysql update of microorganism
		$name = Tool::mysqlEscStr($name);
		$code = empty($code) ? 'NULL' : "'".Tool::mysqlEscStr($code)."'";
		$authors = empty($authors) ? 'NULL' : "'".Tool::mysqlEscStr($authors)."'";
		$notes = empty($notes) ? 'NULL' : "'".Tool::mysqlEscStr($notes)."'";
		$ref = empty($ref) ? 'NULL' : "'".Tool::mysqlEscStr($ref)."'";
		$pref = empty($pref) ? "'0'" : "'1'";
		$prefID = $prefID['id'];
		$pic = empty($pic) ? '' : "ImgPath='".Tool::mysqlEscStr($pic)."',";
		$userid = $this->user['id'];
		$date = date('Y-m-d H:i:s:ms');
		
		# Query string to update microorganism matching given ID
		$upd = "
			UPDATE Microorganisms SET
				Name='$name', Code=$code, Authors=$authors, Notes=$notes,
				Ref=$ref, Pref=$pref, PrefID=$prefID, $taxonid $pic
				UpdBy='$userid', UpdOn='$date', UpdNo=UpdNo+1,
				Categ='$categ', Visib='$visib'
			WHERE ID='$id'
		";
		
		# Update microorganism in the database
		if($this->mysqli->query($upd)) {
			# Synonyms to be added
			if(!empty($synos['name'])) {
				$this->appendSynos($id, $synos);
			}
			
			# Common names to be added
			if(!empty($comns['name'])) {
				$this->appendComn($id, $comns);
			}
			
			# Hosts to be added
			if(!empty($hosts['name'])) {
				$this->appendHost($id, $hosts);
			}
			
			# Synonyms to be removed
			if(!empty($rsynos)) {
				$this->removeSyno($id, $rsynos);
			}
			
			# Common names to be removed
			if(!empty($rcomns)) {
				$this->removeComn($id, $rcomns);
			}
			
			# Hosts to be removed
			if(!empty($rhosts)) {
				$this->removeHost($id, $rhosts);
			}
			
			# Operate on images to be appended or removed
			$img = new Image('micro', null, $this->mysqli, $this->user);
			$img->operate($imgs, $rimgs, $id);
			
			# Marks to be removed
			if(!empty($rmimgs)) {
				$this->removeImgMark($id, $rmimgs);
			}
			
			# Operate on documents to be appended or removed
			$doc = new Document('micro', array('id'=>$id), $this->mysqli, $this->user);
			$doc->operate($docs, $rdocs, $id);
			
			# Operate on locations to be appended or removed
			$loc = new Location('micro', $this->mysqli, $this->user);
			$loc->operate($locs, $rlocs, $id, array('categ'=>$categ, 'visib'=>$visib));
			
			# Operate on resources to be appended or removed
			$rsrc = new Resource('micro', $this->mysqli, $this->user);
			$rsrc->operate($rsrcs, $rrsrcs, $id);
			
			# Upload files to be added
			if(!empty($files['temp']['name'])) {
				$file = new File('micro', $this->mysqli, $this->user);
				$file->append($files['temp'], $id, $categ, $visib);
			}
			
			# Editors to be added
			$coed = new Editor('micro', $this->mysqli, $this->user);
			$coed->operate($coeds, $rcoeds, $id, false);
		}
		
		# Error in updating details
		else {
			$this->notif[] = "Error in updating details of micro {$name}.<br/>";
		}
		
		# Notifications are found
		if(!empty($this->notif)) {
			//echo '<pre>', var_dump($this->notif), '</pre>';
			return false;
		}
		
		# Successfully updated microorganism
		return true;
	} # function update
	
	/**
	* Delete microorganism
	* Delete an existing microorganism from the system
	* 
	* @access public
	* @param string $id Microorganism ID
	* 
	* @return boolean true on success, false on failure
	*/
	public function delete($id) {
		# Query string to delete microorganism
		$del = "UPDATE Microorganisms SET Remove='1' WHERE ID='{$id}'";
		
		# Delete microorganism in the database
		$res = $this->mysqli->query($del);
		
		# Error occurred in deletion
		if(!$res) {
			echo "ERROR: delete";
			return false;
		}
		
		# Successfully deleted microorganism
		return true;
	} # function delete
	
	/**
	* Recover microorganism
	* Recover a deleted microorganism
	* 
	* @access public
	* @param string $id Microorganism ID
	* 
	* @return boolean true on success, false on failure
	*/
	public function recover($id) {
		# Query string to recover microorganism
		$del = "UPDATE Microorganisms SET Remove='0' WHERE ID='{$id}'";
		
		# Recover microorganism in the database
		$res = $this->mysqli->query($del);
		
		# Error occurred in deletion
		if(!$res) {
			echo "ERROR: recover";
			return false;
		}
		
		# Successfully recovered microorganism
		return true;
	} # function recover
	
	/**
	* Upload JSON input for microorganism 
	* Upload json input of microorganisms to be added or updated
	* 
	* @access public
	* @param mixed $inputs JSON inputs
	* @param string $action Action to be performed on uploaded inputs
	* @param mixed $opts Additional parameters
	* 
	* @return array Results on each input processed
	*/
	public function upload($inputs, $action, $opts) {
		$results = array();
		
		# Iterate through each input upload through its path
		foreach($inputs['tmp_name'] as $i => $path) {
			# Temporary input directory
			$inpath = 'data/tmp/'.$this->user['id'].'-'.uniqid();
			# Temporary input name
			$input = $inpath.'/'.Tool::trimout($inputs['name'][$i], 25);
			
			# Make directory and move input to that directory
			# If any encounters an error, continue to next input
			# Add error value to array
			if(!mkdir($inpath, 0777, true) or !move_uploaded_file($path, $input)) {
				echo 'dir';
				$results[$i] = false;
				$results['error']['e'.$i] = $inputs['name'][$i];
				continue;
			}
			
			# Prepare json input string
			# Get contents as string from JSON file
			# Replace all unnecessary characters
			# Encode as utf8, then decode to make a JSON object
			$json = json_decode(utf8_encode(preg_replace( '/\s+/', ' ', file_get_contents($input))));
			
			# Name is empty
			if(!$json or empty($json->identity) or empty($json->identity->name)) {
				echo 'no details';
				# Record error to log
				$results[$i] = false;
				$results['error']['e'.$i] = $inputs['name'][$i];
				
				# Remove temporary input and path
				unlink($input);
				rmdir($inpath);
				continue;
			}
			
			# Microorganism information
			$idt = $json->identity;
			$name = $idt->name; # Scientific name
			$code = empty($idt->code) ? null : $idt->code; # Code
			$authors = empty($idt->authors) ? null : implode(', ', $idt->authors); # Authors//to-do
			$notes = empty($json->notes) ? null : $json->notes; # Notes
			$ref = empty($json->references) ? null : $json->references; # References
			$pref = array('val'=>null, 'id'=>null); # Preferred microorgainsm name//to-do
			
			# Taxonomic position of microorganism
			$taxa = array();
			
			# There is a taxonomic position to be included
			if(!empty($json->taxonomy)) {
				# Iterate through each taxonomic rank
				foreach($json->taxonomy as $rank => $taxon) {
					# Taxon has non-empty name, include in taxa param values
					if(!empty($taxon->name)) {
						$taxa[$rank] = array('name' => $taxon->name, 'code' => empty($taxon->code) ? null : $taxon->code);
					}
				}
			}
			
			# Other names of microorganism
			$synos = array();
			$comns = array();
			# There are other names to be attached
			if(!empty($json->names)) {
				$nm = $json->names;
				
				# Synonyms are not empty
				if(!empty($nm->synonyms)) {
					# Iterate through each synonym in the array
					foreach($nm->synonyms as $syno) {
						# Synonym is to be attached if not empty
						if(!empty($syno->name)) {
							$synos['name'][] = $syno->name; # Synonym
							$synos['auth'][] = empty($syno->author) ? null : $syno->author; # Authors
							$synos['id'][] = empty($syno->id) ? null : $syno->id; # Synonym ID
							$synos['pri'][] = empty($syno->priority) ? null : $syno->priority;
						}
					}
				}
				
				# Common names are not empty
				if(!empty($nm->{"common_names"})) {
					# Iterate through each common names in the array
					foreach($nm->{"common_names"} as $comn) {
						# Common name is to be attached if not empty
						if(!empty($comn->name)) {
							$comns['name'][] = $comn->name; # Common name
							$comns['lang'][] = empty($comn->lang) ? null : $comn->lang; # Language
							$comns['id'][] = empty($comn->id) ? null : $comn->id; # Common name ID
						}
					}
				}
			}
			
			# Initial hosts to be added
			$hosts = array();
			# There are hosts to be added
			if(!empty($json->hosts)) {
				# Iterate through each host in the array
				foreach($json->hosts as $host) {
					# Host name to be added is not empty
					if(!empty($host->name)) {
						$hosts['name'][] = empty($host->name) ? null : $host->name;
						$hosts['code'][] = empty($host->code) ? null : $host->code;
						$hosts['auth'][] = empty($host->authors) ? null : $host->authors;
						$hosts['comn'][] = empty($host->{"common_names"}) ? null : $host->{"common_names"};
						$hosts['id'][] = empty($host->id) ? null : $host->id;
					}
				}
			}
			
			# Initial images to be added
			$imgs = array();
			# There are images to be added
			if(!empty($json->images)) {
				# Iterate through each image
				foreach($json->images as $img) {
					$imgs = checkInputs($imgs, $img);
				}
			}
			
			# Initial documents to be added
			$docs = array();
			# There are documents to be added
			if(!empty($json->documents)) {
				# Iterate through each image
				foreach($json->documents as $doc) {
					$docs = checkInputs($docs, $doc);
				}
			}
			
			# Initial places to be added to distribution list
			$locs = array();
			# There are places to be added
			if(!empty($json->locations)) {
				# Iterate through each place
				foreach($json->locations as $loc) {
					# Either location or the coordinates of that location to be added is not empty
					//if(!empty($dist->name) or !(empty($dist->coordinates[0]) or empty($dist->coordinates[1]))) {
						$locs['val'][] = empty($loc->name) ? null : $loc->name; # Name of place
						$locs['coord'][] = (empty($loc->coordinates[0]) or empty($loc->coordinates[1])) ? null : array($loc->coordinates[0], $loc->coordinates[1]); # Longitude and latitude
						$locs['id'][] = empty($loc->id) ? null : $loc->id; # Location ID
					//}
				}
			}
			
			# Profile photo of microorganism
			$pic = empty($idt->photo) ? null : $idt->photo;
			
			# Initial resources to be added
			$rsrcs = array();
			# There are resources to be added
			if(!empty($json->resources)) {
				# Iterate through each resource
				foreach($json->resources as $rsrc) {
					# Either resource title or notes of resource is not empty
					if(!empty($rsrc->title) or !empty($rsrc->notes)) {
						$rsrcs['title'][] = $rsrc->title; # Title of resource
						$rsrcs['notes'][] = $rsrc->notes; # Additional information
						$rsrcs['links'][] = empty($rsrc->links) ? null : $rsrc->links; # List of hyperlinks
						$rsrcs['id'][] = empty($rsrc->id) ? null : $rsrc->id; # Resource ID
					}
				}
			}
			
			# Initial files to be uploaded (via text)
			$files['path'] = array();
			# There are images or documents to be uploaded
			if(!empty($json->files)) {
				# Iterate through each file
				foreach($json->files as $file) {
					# File to be added has non-empty path
					if(!empty($file->path)) {
						$files['path']['name'][] = $file->path; # Path to image or document
					}
				}
			}
			
			# Initial files to be uploaded (via input file)
			$files['temp'] = isset($_FILES['file']) ? $_FILES['file'] : null;
			
			# Initial settings
			$coeds = array();
			$categ = 'ADV';
			$visib = 'PRV';
			# Settings are to be modified
			if(!empty($json->settings)) {
				# Setting object
				$st = $json->settings;
				
				# List of coeditors
				if(!empty($st->coeditors)) {
					# Iterate through each editor
					foreach($st->coeditors as $coed) {
						# Account email is provided
						if(!empty($coed->email)) {
							$coeds['val'][] = $coed->email; # Email
							$coeds['id'][] = empty($coed->id) ? null : $coed->id; # Account ID
						}
						# Account name is provided
						elseif(!empty($coed->name)) {
							$coeds['val'][] = $coed->name; # Name
							$coeds['id'][] = empty($coed->id) ? null : $coed->id; # Account ID
						}
					}
				}
				
				# Category (Advanced, Basic)
				if(!empty($st->category)) {
					# Normalize category string to lower case
					switch(strtolower($st->category)) {
						# Advanced
						case 'advanced':
						case 'adv':
							$categ = 'ADV';
						break;
						# Basic
						case 'basic':
						case 'bsc':
							$categ = 'BSC';
						break;
					}
				}
				
				# Visibility (Private, Public)
				if(!empty($st->visibility)) {
					# Normalize visibility string to lower case
					switch(strtolower($st->visibility)) {
						# Private
						case 'private':
						case 'prv':
							$visib = 'PRV';
						break;
						# Public
						case 'public':
						case 'pub':
							$visib = 'PUB';
						break;
					}
				}
			}
			
			# Determine which action is to be performed
			switch($action) {
				# Create microorganism
				case 'make':
					# Search microorganism for duplicates in name
					list($res, $size) = $this->search($name, array('c'=>'exact'), 0, 10);
					
					# There are no duplicates found
					if(empty($size)) {
						# Create new microorganism
						$results[$i] = $this->create(
							$name, $code, $authors, !empty($idt->priority), $pref, $taxa, $synos, $comns, $hosts, $locs,
							$notes, $ref, $imgs, $docs, $files, $coeds, $categ, $visib
						);
					}
					# An existing microorganism is found
					else {
						# Get object from returned results
						$micro = $res->fetch_object();
						
						# Update microorganism
						$results[$i] = $this->update(
							$micro->ID, $name, $code, $authors, '1', $pref,
							$taxa, $synos, $comns, $hosts, $notes, $ref, $pic,
							$imgs, $docs, $locs, $rsrcs, $files, $coeds, $categ, $visib,
							null, null, null, null, null, null, null, null, null
						);
					}
				break;
				
				# Update microorganism
				case 'edit':
					# Microorganism ID is empty
					if(empty($opts['id'])) {
						# Search for microorganism
						list($res, $size) = $this->search($name, array('c'=>'exact'), 0, 10);
						
						# An existing microorganism is found
						if(!empty($size)) {
							# Get object in returned results
							$micro = $res->fetch_object();
							# Set as microorganisms ID
							$opts['id'] = $micro->ID;
						}
					}
					
					# Update microorganism
					$results[$i] = $this->update(
						$opts['id'], $name, $code, $authors, $pref,
						$taxa, $synos, $comns, $hosts, $notes, $ref,
						empty($idt->photo) ? null : $idt->photo,
						$imgs, $docs, $locs, $rsrcs, $files, $coeds, $categ, $visib,
						null, null, null, null, null, null, null, null, null
					);
				break;
			}
			
			# An error occurred in doing desired action
			# Returned result is boolean false
			if($results[$i]===false) {
				# Pass error string
				$results['error'][] = $inputs['name'][$i];
			}
			
			# Remove temporary input
			unlink($input);
			# Remove temporary directory
			rmdir($inpath);
		}
		
		# Return all results in processing inputs
		return $results;
	} # function upload
	
	/**
	* Check inputs
	* Identify whether input files included on a JSON input file
	* is another JSON input file (img, doc), a raw filepath, or a JSON object
	* 
	* @access private
	* @param array $array Storage of inputs
	* @param mixed $input Input variable
	*/
	private function checkInputs($array, $input) {
		# Check if variable is string
		if(is_string($input)) {
			# File does not exist
			if(!file_exists($input)) {
				return $array; # Exit procedure
			}
			
			# Get file extension
			$ext = $this->getExt($input);
			
			# Check if it is json file
			if('.json'==$ext) {
				# Store path of json file to array
				$array['json'][] = $input;
			}
			# Path to a file
			else {
				# Get details of file
				$info = pathinfo($input);
				
				# Store to array based on file extension
				$array['.pdf'==$ext ? 'doc' : 'img'][] = array(
					'name'=>$info['basename'], 'type'=>$this->getType($input),
					'tmp_name'=>$input, 'error'=>0, 'size'=>filesize($input)
				);
			}
		}
		else if(!(empty($input->path) or !file_exists($input->path))) {
			# Get details of file
			$info = pathinfo($input->path);
			
			# Store to array based on file extension
			$array['.pdf'==$this->getExt($input->path) ? 'doc' : 'img'][] = array(
				'name'=>$info['basename'], 'type'=>$this->getType($input->path),
				'tmp_name'=>$input->path, 'error'=>0, 'size'=>filesize($input->path),
				'title'=>empty($input->title) ? null : $input->title,
				'notes'=>empty($input->notes) ? null : $input->notes,
				'ref'=>empty($input->references) ? null : $input->references
			);
		}
		
		# Return storage array
		return $array;
	}
	
	/**
	* Get file type
	* Retrieves a file's type
	* 
	* @access public
	* @param string $name Name of file
	* 
	* @return string File's extension
	*/
	public function getType($name) {
		switch($this->getExt($name)) {
			case '.jpg':
			case '.jpeg':
				return 'image/jpeg';
			break;
			
			case '.gif':
				return 'image/gif';
			break;
			
			case '.pdf':
				return 'application/pdf';
			break;
		}
	}
	
	/**
	* Get file extension
	* Retrieves a file's extension
	* 
	* @access public
	* @param string $name Name of file
	* 
	* @return string File's extension
	*/
	public function getExt($name) {
		return strtolower(substr($name, strrpos($name, '.')));
	}
	
	/**
	* Download microorganism
	* Download all allowed details of a microorganism
	* 
	* @access public
	* @param string $id Microorganism ID
	*/
	public function download($id) {
		# Get microorganism based on passed ID
		list($res, $size) = $this->search($id, array('c'=>'id'), null, null);
		
		# Microorganism is not found
		if(empty($size)) {
			# Redirect to microorganisms page with an error
			header('refresh: 0.1; url="http://localhost/microwebph/main.php?img=view&fail=get&id='.$id.'"'); return false;
		}
		
		# Get object from returned results
		$micro = $res->fetch_object();
		
		# Instantial new Setting for doing requests
		$sett = new Setting('micro', null, $this->mysqli, $this->user);
		# Initial condition
		$cond = '';
		
		# Microorganism is basic in category (downloadable)
		if($micro->Categ=='BSC') {
			$cond = "AND T1.Categ='BSC' AND T1.Visib='PUB'";
		}
		# Category is not basic (advanced), check if permitted user
		# User trying to download is not in the permission list
		elseif(!$sett->verify($id)) {
			# Redirect to microorganisms page with an error
			header('refresh: 0.1; url="http://localhost/microwebph/main.php?micro=view&fail=get&id='.$id.'"'); return false;
		}
		
		# Instantiate a new FPDF to create a pdf file for download
		$file = new FPDF();
		$file->SetTitle($micro->Name.' - MicroWebPH'); # Title of downloadable PDF
		$file->SetAuthor('MicroWebPH (c) 2011'); # Author
		$file->AcceptPageBreak(); # Page break is allowed
		$file->AddPage(); # Add a page
		
		# Document header: Title and Description
		$file->SetFont('helvetica', 'b', 10); $file->SetTextColor(72,61,139);
		$file->Write(5, 'MicroWebPH', 'http://localhost/microwebph/');
		$file->SetFont('helvetica', '', 10); $file->SetTextColor(150,150,150);
		$file->Write(5, ' An Online Repository, Management and Retrieval System for Information on Microorganisms'); $file->Ln(); $file->Ln();
		
		# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # 
		
		# Identity
		$file->SetFont('helvetica', 'b', 10); $file->SetTextColor(80,80,80);
		$file->Write(5, 'Identity'); $file->Ln();
		
		# Scientific name
		$file->SetFont('helvetica', '', 10);
		$file->Write(5, 'Name: ');
		$file->SetFont('helvetica', 'i'); $file->SetTextColor(72,61,139);
		$file->Write(5, $micro->Name, "http://localhost/microwebph/main.php?micro=view&id={$id}"); $file->Ln();
		
		# Authors
		$file->SetFont('helvetica', ''); $file->SetTextColor(80,80,80);
		$file->Write(5, 'Authors: '); $file->SetTextColor(0,0,0);
		$file->Write(5,	empty($micro->Authors) ? 'N/A' : $micro->Authors); $file->Ln();
		
		# Code
		$file->SetFont('helvetica', ''); $file->SetTextColor(80,80,80);
		$file->Write(5, 'Code: '); $file->SetTextColor(0,0,0);
		$file->Write(5, empty($micro->Code) ? 'N/A' : $micro->Code); $file->Ln(); $file->Ln();
		
		# Taxonomic position
		$taxa = $this->retrieve('taxon', null, $micro, '', '');
		$file->SetFont('helvetica', 'b', 10); $file->SetTextColor(80,80,80);
		$file->Write(5, 'Taxonomy'); $file->Ln();
		$file->SetFont('helvetica', '', 10); $file->SetTextColor(0,0,0);
		$j = 0;
		
		# Available taxonomic ranks
		$ranks = array('Kingdom', 'Phylum', 'Class', 'Order', 'Family', 'Genus', 'Species');
		# Iterate through each taxon
		foreach($taxa as $taxon) {
			# Include rank if non-empty
			$file->SetX(10); $file->SetTextColor(80,80,80);
			$file->Write(5, $ranks[$j++]);
			$file->SetFont('helvetica', 'i');
			$file->SetX(30); $file->SetTextColor(0,0,0);
			$file->Write(5, $taxon->Name);
			if(!empty($taxon->Code)) {
				 $file->Write(5, ' - '.$taxon->Code);
			} $file->Ln();
		}
		
		# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # 
		
		# Names
		$file->SetX(10); $file->Ln(); $file->SetFont('helvetica', 'b', 10); $file->SetTextColor(80,80,80);
		$file->Write(5, 'Names'); $file->Ln();
		
		# Search synonyms based on passed microorganism ID
		list($synos, $sizesyno) = $this->retrieve('syno', $id, null, '', '');
		# Synonyms are found
		if(!empty($sizesyno)) {
			$file->SetFont('helvetica', '', 10);
			$file->Write(5, "Synonyms"); $file->Ln(); $file->SetTextColor(0,0,0);
			$i = 1;
			
			# Iterate through each synonym and add to list of synonyms
			while($syno = $synos->fetch_object()) {
				$file->SetTextColor(80,80,80); $file->Write(5, $i++.'. '); $file->SetTextColor(72,61,139);
				$file->Write(5, $syno->Name, 'http://localhost/microwebph/main.php?micro=view&id='.$syno->ID); $file->Ln();
			}
		}
		
		# Search common names based on passed microorganism ID
		list($comns, $sizecomn) = $this->retrieve('comn', $id, null, '', '');
		# Common names are found
		if(!empty($sizecomn)) {
			$file->SetFont('helvetica', ''); $file->SetTextColor(80,80,80); $file->SetY($file->GetY()+2);
			$file->Write(5, "Common names"); $file->Ln(); $file->SetTextColor(0,0,0);
			$i = 1;
			
			# Iterate through each synonym and add to list of common names
			while($comn = $comns->fetch_object()) {
				$file->SetTextColor(80,80,80); $file->Write(5, $i++.'. '); $file->SetTextColor(72,61,139);
				$file->Write(5, $comn->Name); $file->Ln();
			}
		}
		
		# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # 
		
		/* # Search all projects associated with the microorganism
		list($projs, $size) = $this->retrieve('proj', $id, null, $cond, '');
		# Assoc. projects are found
		if(!empty($size)) {
			$file->SetFont('helvetica', 'b', 10); $file->SetTextColor(80,80,80);
			$file->Write(5, 'Projects'); $file->SetTextColor(0,0,0); $file->Ln();
			$file->SetFont('helvetica', '', 10);
			$i = 1;
			
			# Iterate throught each project and add to list of projects
			while($proj = $projs->fetch_object()) {
				$file->SetTextColor(80,80,80); $file->Write(5, $i++.'. '); $file->SetTextColor(72,61,139);
				$file->Write(5, $proj->Title, "http://localhost/microwebph/main.php?proj=view&id={$proj->ID}"); $file->Ln();
			}
		} */
		
		# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # 
		
		# Additional information about the microorganism
		if(!empty($micro->Notes)) {
			$file->Ln(); $file->SetFont('helvetica', 'b', 10); $file->SetTextColor(80,80,80);
			$file->Write(5, 'Notes'); $file->Ln();
			$file->SetFont('helvetica', '', 10); $file->SetTextColor(0,0,0);
			$file->Write(5, $micro->Notes); $file->Ln();
		}
		
		# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # 
		
		# Profile image
		if(!empty($micro->ImgPath)) {
			$file->Ln(); $file->SetFont('helvetica', 'b', 10); $file->SetTextColor(80,80,80);
			$file->Write(5, 'Primary image'); $file->Ln(); $file->SetTextColor(0,0,0);
			$file->Image($micro->ImgPath, null, null, null, 50);
		}
		
		# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # 
		
		# Search for images associated with microorganism
		list($imgs, $sizeimg) = $this->retrieve('img', $id, null, $cond, '');
		# Assoc. images are found
		if(!empty($sizeimg)) {
			$file->Ln(); $file->SetFont('helvetica', 'b', 10); $file->SetTextColor(80,80,80);
			$file->Write(5, 'Images'); $file->Ln(); $file->SetTextColor(0,0,0);
			
			# Iterate through each image and add to list of images
			while($img = $imgs->fetch_object()) {
				$file->Image($img->Thumb, null, null, null, 50);
				
				$file->SetFont('helvetica', '', 10); $file->SetTextColor(72,61,139);
				$file->Write(5, $img->Title.' ', 'http://localhost/microwebph/main.php?img=view&id='.$img->ID); $file->Ln(); 
				
				# Image notes
				if(!empty($img->Notes)) {
					$file->SetTextColor(0,0,0);
					$file->Write(5, $img->Notes); $file->Ln();
				}
				$file->Ln();
			}
		}
		
		# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # 
		
		# Search image marks associated with the microorganism
		list($marks, $sizemark) = $this->retrieve('mark', $id, null, $cond, '');
		# Assoc. marks are found
		if(!empty($sizemark)) {
			# Iterate through each marks
			while($mark = $marks->fetch_object()) {
				$file->Image($mark->Thumb, null, null, 0, 50);
				
				$file->SetFont('helvetica', '', 10); $file->SetTextColor(72,61,139);
				$file->Write(5, $mark->Title.' ', 'http://localhost/microwebph/main.php?img=view&id='.$mark->ID); $file->Ln(); 
				
				# Image mark notes
				if(!empty($mark->Notes)) {
					$file->SetTextColor(0,0,0);
					$file->Write(5, $mark->Notes); $file->Ln();
				} $file->Ln();
			}
		}
		
		# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # 
		
		# Search locations associated with microorganism
		list($locs, $sizeloc) = $this->retrieve('loc', $id, null, $cond, '');
		# Assoc. locations are found
		if(!empty($sizeloc)) {
			$file->Ln(); $file->SetFont('helvetica', 'b', 10); $file->SetTextColor(80,80,80);
			$file->Write(5, 'Locations'); $file->Ln(); $file->SetFont('helvetica', '', 10); $file->SetTextColor(0,0,0);
			$i = 1;
			
			# Add each location to list of locations
			while($loc = $locs->fetch_object()) {
				$file->SetTextColor(80,80,80); $file->Write(5, $i++.'. '); $file->SetTextColor(72,61,139);
				$file->Write(5, $loc->Name.(empty($loc->Notes) ? '' : ': '.$loc->Notes), 'http://localhost/microwebph/main.php?loc=view&id='.$loc->ID); $file->Ln();
			}
		}
		
		# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # 
		
		# Output file for saving
		$file->Output(str_replace(' ', '_', Tool::trimout($micro->Name))."-[{$micro->Code}]-microwebph.pdf", 'i');
	} # function download
	
	/**
	* Preferred microorganism
	* Prepare microorganism query input of its preferred name
	* 
	* @access private
	* @param string $name Name of microorganism
	* @param array $pref Contains name or id of preferred microorganism
	*
	* @return string Preferred microorganism's ID
	*/
	private function doPrefMicro($name, $pref) {
		# Set preferred ID
		if(!empty($pref['id'])) {
			$prefid = "'".$pref['id']."'";
		}
		# Preferred value is present and does not conflict with own microorganism
		elseif(!empty($pref['val']) and $name!=$pref['val']) {
			# Search string to search preferred microorganism's name
			$sel = "
				SELECT T1.ID FROM Microorganisms AS T1 INNER JOIN MicroSynos AS T2
					ON T1.ID=T2.PID WHERE T1.Name='{$pref['val']}' OR T1.Name='{$name}'
			";
			
			# Query search string in mysql
			$res = $this->mysqli->query($sel);
			
			# Successful search and at least one result is returned
			if($res and !empty($res->num_rows)) {
				$pmicro = $res->fetch_object();
				# Set found microorganism ID as preferred ID
				$prefid = "'".$pmicro->ID."'";
			}
			else {
				# Microorganism not found
				$prefid = 'NULL';
			}
		}
		else {
			# Empty preferred name or conflict in own microorganism's name
			$prefid = 'NULL';
		}
		
		# Preferred microorganism's ID
		return $prefid;
	} # function doPrefMicro
	
	/**
	* Taxonomic position of microorganism
	* Prepare microorganism query input of its taxonomic position
	* 
	* @access private
	* @param array $taxon Taxonomic ranks with values
	*
	* @return string Taxonomic position of microorganism
	*/
	private function doTaxonMicro($taxon) {
		# Empty taxonomic position, set all ranks to null
		if(empty($taxon)) {
			$taxonid = "NULL, NULL, NULL, NULL, NULL, NULL, NULL, ";
		}
		else {
			# initial taxon's id
			$taxonid = "";
			
			# Iterate through each taxon
			foreach($this->ranks as $i => $rank) {
				# Empty name
				if(empty($taxon[$rank]['name'])) {
					$taxonid .= 'NULL, ';
				}
				else {
					# Empty taxonomic rank id
					if(empty($taxon[$rank]['id'])) {
						# Select rank
						$restax = $this->mysqli->query("SELECT * FROM {$this->taxatb[$rank]} WHERE Name='{$taxon[$rank]['name']}'");
						
						# Rank found
						if($restax->num_rows == 1) {
							# Set rank ID
							$objtax = $restax->fetch_object();
							$taxon[$rank]['id'] = $objtax->ID;
						}
						else {
							# Generate ID
							$taxon[$rank]['id'] = Tool::generateID('taxon');
							$subtax = "";
							
							# Iterate taxa (highest to lowest)
							for($j=0; $j<$i; $j++) {
								$subtax .= (empty($taxon[$this->ranks[$j]]['id']) ? 'NULL, ' : "'{$taxon[$this->ranks[$j]]['id']}', ");
							}
							
							# Insert string for new taxon
							$instax = "
								INSERT INTO {$this->taxatb[$rank]} VALUES (
									'{$taxon[$rank]['id']}', '{$taxon[$rank]['name']}', '{$taxon[$rank]['code']}', {$subtax} '{$this->user['id']}', '".date('Y-m-d H:i:s:ms')."', '0'
								)
							";
							
							# Create new taxon
							$this->mysqli->query($instax) or die();
						}
					}
					
					# Set taxon id
					$taxonid .=  "'{$taxon[$rank]['id']}', ";
				}
			}
		}
		
		# Taxonomic id's
		return substr($taxonid, 0, -2);
	} # function doTaxonMicro
	
	/**
	* New Synonym
	* Create new microorganism as a synonym
	* 
	* @access private
	* @param string $name Synonym
	* @param mixed $auth Scientific authors of synonym
	* @param string $id Microorganism where synonym is associated
	*
	* @return boolean True on success, false on failure
	*/
	public function createMicroSyno($name, $auth, $pri, $id) {
		# Create new microorganism
		$mid = $this->create(
			$name, null, $auth, $pri, array('id'=>$id),
			null, null, null, null, null, null, null, null, null, null,
			null, 'ADV', 'PUB'
		);
		
		# An error occurred
		if(!$mid) {
			$this->notif[] = 'ERROR: ins syno as micro';
			return false;
		}
		
		# Created synonym successfully
		return $mid;
	} # function createMicroSyno
	
	/**
	* Append Synonyms
	* Append lists of synonyms to a microorganism
	* 
	* @access public
	* @param string $id Microorganism ID
	* @param array $synos List of synonyms
	*/
	public function appendSynos($id, $synos) {
		# Iterate through each synonym
		foreach($synos['name'] as $i => $name) {
			# Synonym ID is empty so search for synonym
			if(empty($synos['id'][$i])) {
				# Synonym is empty, do nothing else
				if(empty($name)) continue;
				
				# Search for microorganism bearing the same name
				$sel = "SELECT ID FROM Microorganisms WHERE Name='{$name}'";
				$res = $this->mysqli->query($sel);
				
				# Microorganism is found
				if($res and !empty($res->num_rows)) {
					$micro = $res->fetch_object();
					# Add synonym to that microorganism's synonyms list
					$this->findToAddSyno($name, $synos['auth'][$i], $synos['pri'][$i], $id);
					
					# Set preference of synonym to that microorganism
					$upd = "UPDATE Microorganisms SET PrefID='{$id}' WHERE ID='{$micro->ID}'";
					if(!$this->mysqli->query($upd)) {
						$this->notif[] = "ERROR: upd micro as syno";
					}
				}
				else {
					# Synonym is not found, then create new synonym
					$this->findToAddSyno($name, $synos['auth'][$i], $synos['pri'][$i], $id);
				}
			}
			else {
				# Append synonym ID to microorganism
				$this->appendSyno($id, $synos['id'][$i]);
			}
		}
	} # function appendSynos
	
	/**
	* Find synonym
	* Find synonyms to be appended to microorganism
	* If not found, create new microorganism for that synonym
	* 
	* @access private
	* @param string $name Name of synonym
	* @param string $auth Scientific authors of synonym
	* @param string $id ID of preferred microorganism
	*
	* @return string Synonym ID
	*/
	private function findToAddSyno($name, $auth, $pri, $id) {
		# Search microorganism bearing the name (synonym)
		list($res, $size) = $this->search($name, array('c'=>'exact'), null, 1);
		
		# Microorganism is found
		if($res and !empty($res->num_rows)) {
			$syno = $res->fetch_object();
			# Append synonym to microorganism
			$this->appendSyno($id, $syno->ID);
			# Return synonym ID
			return $syno->ID;
		}
		# Microorganism is not found, thus create a new synonym
		else {
			# Create new synonym
			$sid = $this->createMicroSyno($name, $auth, $pri, $id);
			
			# Created new synonym successfully
			if($sid!==false) {
				# Append synonym to that microorganism
				$this->appendSyno($id, $sid);
				# Return synonym ID
				return $sid;
			}
		}
	} # function findToAddSyno
	
	/**
	* Append synonym
	* Append microorganism as a synonym to preferred microorganism
	* 
	* @access private
	* @param string $id Preferred microorganism's ID
	* @param string $sid Synonym's ID
	*/
	private function appendSyno($id, $sid) {
		# Check if synonym is already binded to microorganism
		$sel = "SELECT * FROM MicroSynos WHERE PID='$id' AND CID='$sid'";
		$res = $this->mysqli->query($sel);
		
		# Synonym is not yet binded
		if($res and empty($res->num_rows)) {
			# Append synonym to microorganism
			$ins = "
				INSERT INTO MicroSynos VALUES (
					'{$id}', '{$sid}', '{$this->user['id']}', '".date('Y-m-d H:i:s:ms')."'
				)
			";
			
			# An error occurred in appending
			if($this->mysqli->query($ins)) {
				$upd = "UPDATE Microorganisms SET PrefID='$id' WHERE ID='$sid'";
				
				if(!$this->mysqli->query($upd)) {
					$this->notif[] = "ERROR: upd micro syno $id, $sid";
				}
			}
			else {
				$this->notif[] = "ERROR: ins micro syno $id, $sid";
			}
		}
	} # function appendSyno
	
	/**
	* Append common name
	* Append common name to microorganism
	* 
	* @access private
	* @param string $id Microorganism's ID
	* @param array $comns Common names
	*/
	private function appendComn($id, $comns) {
		# Iterate through each common name
		foreach($comns['name'] as $i => $comn) {
			# Common name ID is empty, so search for common name based on name provided
			if(empty($comns['id'][$i])) {
				# There is no name provided, so skip this
				if(empty($comn)) continue;
				
				# Prepare values for mysql search
				$comn = Tool::mysqlEscStr($comn);
				$lang = empty($comns['lang'][$i]) ? '' : "AND Lang='".Tool::mysqlEscStr($comns['lang'][$i])."'";
				
				# Search common names
				$sel = "SELECT * FROM Comnames WHERE Name='$comn' $lang LIMIT 1"; //todo: author select
				$res = $this->mysqli->query($sel);
				
				# No common names are found
				if($res and empty($res->num_rows)) {
					# Create new common name
					$cid = Tool::generateID('comn');
					$comn = Tool::mysqlEscStr($comn);
					$lang = empty($comns['lang'][$i]) ? 'NULL' : "'".Tool::mysqlEscStr($comns['lang'][$i])."'";
					$date = date('Y-m-d H:i:s:ms');
					
					# Query string to insert new common name
					$ins = "INSERT INTO Comnames VALUES ( '$cid', '$comn', $lang, 0, '{$this->user['id']}', '$date', '0' )";
					
					# Successfully added common name
					if($this->mysqli->query($ins)) {
						$date = date('Y-m-d H:i:s:ms');
						
						# Append common name to microorganism
						$ins = "INSERT INTO MicroComns VALUES ('$id', '$cid', '{$this->user['id']}', '$date')";
						
						# An error occurred
						if(!$this->mysqli->query($ins)) {
							$this->notif[] = "ERROR: ins micro comn 1<br/>";
						}
					}
				}
				else {
					# Get common name and update number of microorganisms bearing the same common name
					$comn = $res->fetch_object();
					$upd = "UPDATE Comnames SET Size=Size+1 WHERE ID='{$comn->ID}'";
					
					# Append common name to microorganism
					if($this->mysqli->query($upd)) {
						$ins = "
							INSERT INTO MicroComns VALUES (
								'$id', '{$comn->ID}', '{$this->user['id']}', '".date('Y-m-d H:i:s:ms')."'
							)
						";
						
						# An error occurred
						if(!$this->mysqli->query($ins)) {
							$this->notif[] = "ERROR: ins micro comn 2<br/>";
						}
					}
				}
			}
			else {
				# Append common name to microorganism
				$ins = "
					INSERT INTO MicroComns VALUES (
						'{$id}', '{$comns['id'][$i]}', '{$this->user['id']}', '".date('Y-m-d H:i:s:ms')."'
					)
				";
				
				# An error occurred
				if(!$this->mysqli->query($ins)) {
					$this->notif[] = "ERROR: ins micro comn 3<br/>";
				}
			}
		}
	} # function appendComn
	
	/**
	* Append host
	* Append host to microorganism
	* 
	* @access private
	* @param string $id Microorganism's ID
	* @param array $hosts Host names and ids
	*/
	private function appendHost($id, $hosts) {
		# Iterate through each host
		foreach($hosts['name'] as $i => $name) {
			# Empty host ID, so search host
			if(empty($hosts['id'][$i])) {
				# No name provided; skip host
				if(empty($name)) continue;
				
				# Search for host in the database
				$name = Tool::mysqlEscStr($name);
				$ccode = empty($hosts['code'][$i]) ? '' : "AND Code LIKE '%{$hosts['code'][$i]}%' ";
				$cauth = empty($hosts['auth'][$i]) ? '' : "AND Authors LIKE '%".Tool::mysqlEscStr($hosts['auth'][$i])."%' ";
				$sel = "SELECT * FROM Hosts WHERE Name LIKE '%$name%' $ccode $cauth LIMIT 1"; //todo: author select
				$res = $this->mysqli->query($sel);
				
				# Host is not found
				if(empty($res->num_rows)) {
					# Create new host
					$hid = Tool::generateID('host');
					$ccode = empty($hosts['code'][$i]) ? 'NULL' : "'{$hosts['code'][$i]}'";
					$cauth = empty($hosts['auth'][$i]) ? 'NULL' : "'".Tool::mysqlEscStr($hosts['auth'][$i])."'";
					$ins = "
						INSERT INTO Hosts VALUES (
							'{$hid}', '$name', $ccode, $cauth, 0, '{$this->user['id']}', '".date('Y-m-d H:i:s:ms')."', '0'
						)
					";
					
					# Insert host to database
					if($this->mysqli->query($ins)) {
						# Append host to microorganism
						$ins = "INSERT INTO MicroHosts VALUES ('$id', '$hid', '{$this->user['id']}', '".date('Y-m-d H:i:s:ms')."')";
						
						# An error occurred
						if(!$this->mysqli->query($ins)) {
							$this->notif[] = "ERROR: ins micro host 1<br/>";
						}
						
						# Common name of hos, if not empty, append to host
						if(!empty($hosts['comn'][$i])) {
							$this->appendHostComnames($hid, $hosts['comn'][$i]);
						}
					}
				}
				else {
					# Get host object and increment size of microorganisms associated with it
					$host = $res->fetch_object();
					$upd = "UPDATE Hosts SET Size=Size+1 WHERE ID='{$host->ID}'";
					
					# Update host entry
					if($this->mysqli->query($upd)) {
						# Append host to microorganism
						$ins = "
							INSERT INTO MicroHosts VALUES (
								'$id', '{$host->ID}', '{$this->user['id']}', '".date('Y-m-d H:i:s:ms')."'
							)
						";
						
						# An error occurred
						if(!$this->mysqli->query($ins)) {
							$this->notif[] = "ERROR: ins micro host 2<br/>";
						}
					}
				}
			}
			else {
				# Append host to microorganism
				$ins = "
					INSERT INTO MicroHosts VALUES (
						'{$id}', '{$hosts['id'][$i]}', '{$this->user['id']}', '".date('Y-m-d H:i:s:ms')."'
					)
				";
				
				# An error occurred
				if(!$this->mysqli->query($ins)) {
					$this->notif[] = "ERROR: ins micro host 3<br/>";
				}
			}
		}
	} # function appendHost
	
	/**
	* Append host's common names
	* Append common names of hosts of a microorganism
	* 
	* @access private
	* @param string $id Microorganism's ID
	* @param array $hcomns Common names of hosts
	*/
	public function appendHostComnames($hid, $hcomns) {
		# Iterate through each host common name
		foreach($hcomns as $i => $hcomn) {
			# Not common name is found, skip
			if(empty($hcomn)) continue;
			
			# Search common name of host
			$sel = "SELECT * FROM HostComnames WHERE Name LIKE '%".mysql_real_escape_string($hcomn)."%' LIMIT 1";
			$res = $this->mysqli->query($sel);
			
			# Common name is not found
			if(empty($res->num_rows)) {
				# Create new host common name
				$hcid = Tool::generateID('hcomn');
				
				$ins = "
					INSERT INTO HostComnames VALUES (
						'{$hcid}', '".Tool::mysqlEscStr($hcomn)."',
						".(empty($hcomns['lang'][$i]) ? 'NULL' : "'{$hcomns['lang'][$i]}'").",
						0, '{$this->user['id']}', '".date('Y-m-d H:i:s:ms')."', '0'
					)
				";
				
				# Append common name to host
				if($this->mysqli->query($ins)) {
					$ins = "
						INSERT INTO HostComns VALUES (
							'{$hid}', '{$hcid}', '{$this->user['id']}', '".date('Y-m-d H:i:s:ms')."'
						)
					";
					
					# An error occurred
					if(!$this->mysqli->query($ins)) {
						$this->notif[] = "ERROR: ins host hcomn 1<br/>";
					}
				}
			}
			else {
				# Check to see if common name is already binded to host
				$hcomn = $res->fetch_object();
				$sel = "SELECT * FROM HostComns WHERE PID='$hid' AND CID='{$hcomn->ID}' ";
				$res = $this->mysqli->query($sel);
				
				# Common name is not yet appended to host
				if($res and empty($res->num_rows)) {
					$upd = "UPDATE HostComnames SET Size=Size+1 WHERE ID='{$hcomn->ID}'";// if($this->mysqli->query($upd)) {
					
					# Update size of hosts with the same common name
					if($this->mysqli->query($upd)) {
						# Append common name to host
						$ins = "
							INSERT INTO HostComns VALUES (
								'{$hid}', '{$hcomn->ID}', '{$this->user['id']}', '".date('Y-m-d H:i:s:ms')."'
							)
						";
						
						# An error occurred
						if(!$this->mysqli->query($ins)) {
							$this->notif[] = "ERROR: ins host hcomn 2<br/>";
						}
					}
				}
			}
		}
	} # function appendHostComnames
	
	/**
	* Remove synonyms
	* Remove synonyms binded to microorganism
	* 
	* @access private
	* @param string $id Microorganism's ID
	* @param array $synoID IDs of synonyms to be removed
	*
	* @return boolean True on success, false on failure
	*/
	private function removeSyno($id, $sid) {
		$sid = implode("', '", $sid);
		
		# Remove all synonyms binded to microorganism
		$del = "DELETE FROM MicroSynos WHERE PID='{$id}' AND CID IN ('".$sid."')";
		
		# An error occurred
		if($this->mysqli->query($del)) {
			$upd = "UPDATE Microorganisms SET PrefID=NULL WHERE ID IN ('".$sid."')";
			
			if($this->mysqli->query($upd)) {
				# Successfully removed binded synonyms
				return true;
			}
			else {
				$this->notif[] = "ERROR: upd micro syno $id, '$sid'";
			}
		}
		else {
			$this->notif[] = "ERROR: del micro syno $id, '$sid'";
		}
		
		return false;
	} # function removeSyno
	
	/**
	* Remove common names
	* Remove common names binded to microorganism
	* 
	* @access private
	* @param string $id Microorganism's ID
	* @param array $comnID IDs of common names to be removed
	*
	* @return boolean True on success, false on failure
	*/
	private function removeComn($id, $comnID) {
		# Remove all common names binded to microorganism
		$del = "DELETE FROM MicroComns WHERE PID='{$id}' AND CID IN ('".implode("', '", $comnID)."')";
		
		# An error occurred
		if(!$this->mysqli->query($del)) {
			$this->notif[] = "ERROR: del micro comn";
			return false;
		}
		
		# Successfully removed binded common names
		return true;
	} # function removeComn
	
	/**
	* Remove host
	* Remove hosts binded to microorganism
	* 
	* @access private
	* @param string $id Microorganism's ID
	* @param array $hostID IDs of hosts to be removed
	*
	* @return boolean True on success, false on failure
	*/
	private function removeHost($id, $hostID) {
		# Remove all hosts binded to microorganism
		$del = "DELETE FROM MicroHosts WHERE PID='{$id}' AND CID IN ('".implode("', '", $hostID)."')";
		
		# An error occurred
		if(!$this->mysqli->query($del)) {
			$this->notif[] = "ERROR: del micro host";
			return false;
		}
		
		# Successfully removed binded hosts
		return true;
	} # function removeHost
	
	/**
	* Remove image marks
	* Remove image marks binded to microorganism
	* 
	* @access public
	* @param string $id Microorganism's ID
	* @param array $rmimgs IDs of marks to be removed
	*
	* @return boolean True on success, false on failure
	*/
	public function removeImgMark($id, $rmimgs) {
		# Remove all marks binded to microorganism
		$del = "DELETE FROM MarkMicros WHERE MicroID='{$id}' AND ImgID IN ('".implode("', '", $rmimgs)."')";
		
		# An error occurred
		if(!$this->mysqli->query($del)) {
			$this->notif[] = "ERROR: del mark-img<br/>";
			return false;
		}
		
		# Successfully removed binded marks
		return true;
	} # function removeImgMark
	
	/**
	* Process appended and remove microorganisms
	* Process on all microorganisms associated with an area
	* which are to be appended or removed
	* 
	* @access public
	* @param array $addl Microorganisms to be appended
	* @param array $rmvl Microorganisms to be removed
	* @param string $id ID of area
	* @param boolean $new Microorganisms to be appended, if non-existent, must be created
	*/
	public function operate($addl, $rmvl, $id, $new) {
		if(!empty($addl["val"])) $this->append($addl, $id, $new);
		if(!empty($rmvl)) $this->remove($rmvl, $id);
	} # function operate
	
	/**
	* Append microorganisms
	* Append microorganisms associated to that area
	* 
	* @access public
	* @param array $addl Microorganisms to be appended
	* @param string $id ID of area
	* @param boolean $new Microorganisms to be appended, if non-existent, must be created
	*/
	public function append($addl, $id, $new) {
		# Iterate throught each microorganisms
		foreach($addl['val'] as $i => $value) {
			# Name is empty, skip this
			if(empty($value)) continue;
			
			# ID is not provided
			if(empty($addl['id'][$i])) {
				# Search for microorganism bearing the name
				$res = $this->mysqli->query("SELECT ID FROM Microorganisms WHERE Name='{$value}'");
				
				# Microorganism is found
				if($res and !empty($res->num_rows)) {
					$micro = $res->fetch_object();
					# Append microorganism to that area
					$ins = "INSERT INTO {$this->table} ({$this->pid}, {$this->cid}, Ext, CrtBy, CrtOn) VALUES ('{$id}', '{$micro->ID}', '1', '{$this->user['id']}', '".date('Y-m-d H:i:s:ms')."')";
				}
				# Microorganis is not found and so it must be created
				elseif(isset($new) and $new) {
					# Create microorganism
					$newID = $this->create($value,
						empty($addl['code'][$i]) ? null : $addl['code'][$i],
						empty($addl['auth'][$i]) ? null : $addl['auth'][$i],
						1, null, null, null, null, null, null,
						empty($addl['note'][$i]) ? null : $addl['note'][$i],
						empty($addl['ref'][$i]) ? null : $addl['ref'][$i],
						null, null, null, null, 'ADV', 'PUB');
					
					# Successfully created microorganism
					if(!empty($newID)) {
						# Append microorganism to that area
						$ins = "INSERT INTO {$this->table} ({$this->pid}, {$this->cid}, Ext, CrtBy, CrtOn) VALUES ('{$id}', '{$newID}', '0', '{$this->user['id']}', '".date('Y-m-d H:i:s:ms')."')";
					}
				}
			}
			else {
				# Append microorganism to that area
				$ins = "INSERT INTO {$this->table} ({$this->pid}, {$this->cid}, Ext, CrtBy, CrtOn) VALUES ('{$id}', '{$addl['id'][$i]}', '1', '{$this->user['id']}', '".date('Y-m-d H:i:s:ms')."')";
			}
			
			# An insert query has to be performed
			if(!empty($ins)) {
				# Do mysql query to append microorganism to area
				if(!$this->mysqli->query($ins)) {
					$this->notif[] = "ERROR: ins area-micro {$id} $value.<br/>";
				}
			}
		}
	} # function append
	
	/**
	* Remove microorganisms
	* Remove microorganisms associated to that area
	* 
	* @access public
	* @param array $rmvl Microorganisms to be removed
	* @param string $id ID of area
	*/
	public function remove($rmvl, $id) {
		# Delete microorganism-area entry from respective relational tables
		$del = "DELETE FROM {$this->table} WHERE {$this->pid}='{$id}' AND {$this->cid} IN ('".implode("', '", $rmvl)."')";
		
		# An error occurred
		if(!$this->mysqli->query($del)) {
			$this->notif[] = "ERROR: rem micro<br/>";
		}
	} # function remove
	
	/**
	* Edit taxonomy
	* Edit taxonomic position/rank's name and/or Code
	* 
	* @access public
	* @param string $id ID of taxon
	* @param string $rank Rank
	* @param string $name Name
	* @param string $code Code
	*/
	public function editTaxon($id, $rank, $name, $code) {
		# Update taxoonomic position's name and/or rank
		$upd = "UPDATE {$this->taxatb[$rank]} SET Name='$name', Code='$code' WHERE ID='$id'";
		
		# An error occurred
		if(!$this->mysqli->query($upd)) {
			$this->notif[] = "ERROR: upd taxon<br/>";
			return false;
		}
		
		# Successfully updated taxon
		return true;
	} # function editTaxon
	
	/**
	* Fetch microorganisms
	* Fetch microorganisms associated with an area
	* 
	* @access public
	* @param string $id ID of area
	* @param int $start Start of return results
	*/
	public function fetch($id, $start) {
		# Project
		if($this->area=='proj') {
			# Select all microorganisms which are associated to project
			$sel = "
				SELECT T1.* FROM Microorganisms AS T1 INNER JOIN {$this->table} AS T2
					ON T1.ID=T2.CID AND T2.PID='{$id}' ORDER BY T2.CrtOn LIMIT {$start}, 10
			";
		}
		# Any area
		else {
			# Select all microorganisms which are associated to an area
			$sel = "
				SELECT T1.* FROM Microorganisms AS T1 INNER JOIN {$this->table} AS T2
					ON T1.ID=T2.PID AND T2.CID='{$id}' ORDER BY T2.CrtOn LIMIT {$start}, 10
			";
		}
		
		# Do mysql query to search all microorganisms
		$res = $this->mysqli->query($sel);
		
		# Assoc. microorganism are found
		if($res and !empty($res->num_rows)) {
			# List all microorganisms ?>
			<output style="display:none"> <?php
				# Iterate through each microorganism
				while($micro = $res->fetch_object()) { ?>
					<li class="micro">
						<a href="main.php?micro=view&id=<?php echo $micro->ID ?>" class="ital"><?php echo $micro->Name ?></a>
							<span class="dim"><?php echo $micro->Authors ?></span>
						<button type="button" class="remove icon read" data-area="micro" data-id="<?php echo $micro->ID ?>"></button>
					</li> <?php
				} ?>
			</output> <?php
		}
	} # function fetch
	
	/**
	* Display all microorganisms
	* Retrieve all contents of microorganisms on a page
	* 
	* @access public
	* @param array $queries IDs of microorganisms
	*/
	public function displayAll($queries, $opts) { ?>
		<output> <?php
			if($results = $this->search($queries, $opts, 0, 10)) {
				while($result = $results[0]->fetch_object()) {
					$this->displayContent($result, false);
				}
			} ?>
		</output> <?php
	}
	
	/**
	* Guess microorganism
	* Provides a list of microorganisms (guess) on user input
	* Makes selection of microorganism and id faster
	* 
	* @access public
	* @param string $query Microorganism's name or taxonomic position to be searched
	*/
	public function guess($query) {
		# Search for microorganisms matching the query string and constrains passed
		$micros = $this->search($query, $_REQUEST, 0, 10);
		
		# Microorganism is not found
		if(!$micros or empty($micros[1])) {
			return false;
		}
		
		# Iterate through each found microorganisms
		while($micro = $micros[0]->fetch_object()) { ?>
			<div class="guess micro" data-id="<?php echo $micro->ID ?>" data-value="<?php echo $micro->Name ?>" data-code="<?php echo $micro->Code ?>" tabindex="0"
				<?php if(strlen($micro->Name) > 50) { ?> data-tool="{'head':'<?php echo $micro->Name ?>'}" <?php } ?>>
				<a href="main.php?micro=view&id=<?php echo $micro->ID ?>"> <?php
					echo Tool::truncate($micro->Name, 50); ?></a>
			</div> <?php
		}
		
		$tax = '';
		if(!(!isset($_REQUEST['a']) or $_REQUEST['a']!='taxong' or !isset($_REQUEST['i']))) {
			$tax = '&c=taxon&rnk='.$_REQUEST['i'];
		}
		
		if($_REQUEST['s']=='true') { ?>
			<div class="guess-header micro query">
				<a href="main.php?micro=view&q=<?php echo urlencode($query).$tax ?>" target="_blank" title="<?php echo $query ?>"><?php echo Tool::truncate($query, 30) ?></a>
				<span class="right bold none" title="<?php echo ($found = $micros[0]->num_rows.' of '.$micros[1]).' items found' ?>"><?php echo $found ?></span>
			</div> <?php
		}
	} # function guess
	
	/**
	* Retrieve details
	* Get all details associated with microorganism to be displayed
	* 
	* @access private
	* @param string $area Area where microorganism is associated
	* @param string $id ID of microorganism
	* @param mixed $micro Microorganism object
	* @param string $cond Additional constraints
	* @param string $limit Limit to search results
	* 
	* @return mixed Returned results on search
	*/
	private function retrieve($area, $id, $micro, $cond, $limit) {
		# Select size of returned rows after search
		$selSize = "SELECT FOUND_ROWS()";
		
		# Taxonomic positions
		if($area=='taxon') {
			$result = array();
			$keys = $this->taxaid;
			
			# Iterate through each rank
			foreach($this->ranks as $i => $rank) {
				# Rank is set and must be found
				if(isset($micro->$keys[$i])) {
					$res = $this->mysqli->query("SELECT * FROM {$this->taxatb[$rank]} WHERE ID='{$micro->$keys[$i]}'");
					# Include object in the search to the results
					$result[$rank] = $res->fetch_object();
				}
			}
			
			# Return results
			return $result;
		}
		
		# Associated areas to microorganism
		switch($area) {
			# Preferred microorganism
			case 'pref':
				$sel = "
					SELECT SQL_CALC_FOUND_ROWS * FROM Microorganisms WHERE ID='{$id}' AND Remove='0'  ORDER BY CrtOn 
				";
			break;
			
			# Synonyms
			case 'syno':
				$sel = "
					SELECT SQL_CALC_FOUND_ROWS * FROM Microorganisms AS T1 INNER JOIN MicroSynos AS T2
					ON T1.ID=T2.CID WHERE T2.PID='{$id}' AND T1.Remove='0' ORDER BY T2.CrtOn
				";
			break;
			
			# Common names
			case 'comn':
				$sel = "
					SELECT SQL_CALC_FOUND_ROWS * FROM Comnames AS T1 INNER Join MicroComns AS T2 ON T1.ID=T2.CID WHERE T2.PID='{$id}' ORDER BY T2.CrtOn 
				";
			break;
			
			# Hosts
			case 'host':
				$sel = "
					SELECT SQL_CALC_FOUND_ROWS * FROM Hosts AS T1 INNER Join MicroHosts AS T2 ON T1.ID=T2.CID WHERE T2.PID='{$id}' ORDER BY T2.CrtOn 
				";
			break;
			
			# Projects
			case 'proj':
				$sel = "
					SELECT SQL_CALC_FOUND_ROWS DISTINCT T1.* FROM Projects AS T1 INNER JOIN ProjMicros AS T2
						ON T1.ID=T2.PID AND T2.CID='{$id}' AND T1.Remove='0' {$cond} ORDER BY T2.CrtOn {$limit}
				";
			break;
			
			# Images
			case 'img':
				$sel = "
					SELECT SQL_CALC_FOUND_ROWS DISTINCT T1.* FROM Images AS T1 INNER JOIN MicroImgs AS T2
						ON T1.ID=T2.CID AND T2.PID='{$id}' AND T1.Remove='0' {$cond} ORDER BY T2.CrtOn {$limit}
				";
			break;
			
			# Documents
			case 'doc':
				$sel = "
					SELECT SQL_CALC_FOUND_ROWS DISTINCT T1.* FROM Documents AS T1 INNER JOIN MicroDocs AS T2
						ON T1.ID=T2.CID AND T2.PID='{$id}' AND T1.Remove='0' {$cond} ORDER BY T2.CrtOn {$limit}
				";
			break;
			
			# Image marks
			case 'mark':
				$sel = "
					SELECT SQL_CALC_FOUND_ROWS DISTINCT T1.* FROM Images AS T1 INNER JOIN MarkMicros AS T2
						ON T1.ID=T2.ImgID AND T2.MicroID='{$id}' AND T1.Remove='0' {$cond} ORDER BY T2.CrtOn {$limit}
				";
			break;
			
			# Locations
			case 'loc':
				$sel = "
					SELECT SQL_CALC_FOUND_ROWS DISTINCT T1.* FROM Locations AS T1 INNER JOIN MicroLocs AS T2
						ON T1.ID=T2.CID AND T2.PID='{$id}' AND T1.Remove='0' {$cond} ORDER BY T2.CrtOn {$limit}
				";
			break;
			
			# Resources
			case 'rsrc':
				$sel = "
					SELECT SQL_CALC_FOUND_ROWS DISTINCT T1.* FROM Resources AS T1 INNER JOIN MicroRsrcs AS T2
						ON T1.ID=T2.CID AND T2.PID='{$id}' AND T1.Remove='0' {$cond} ORDER BY T2.CrtOn {$limit}
				";
			break;
		}
		
		# Do mysql query to search associated area of microorganism
		$res = $this->mysqli->query($sel);
		# Get size of returned rows
		$size = $this->mysqli->query($selSize);
		$size = $size->fetch_row();
		
		# Return result rows and size of rows
		return array($res, $size[0]);
	} # function retrieve
	
	/**
	* Display main microorganism stage
	* List all microorganisms in the main page
	* 
	* @access public
	* @param mixed $micros List of microorganisms from returned search results
	* @param integer $size Size of rows from returned search results
	* @param string $query Query string that was searched for
	* @param array $opts Optional parameters
	* @param integer $start Starting row in mysql returned results
	*/
	public function displayMain($micros, $size, $query, $opts, $start) {
		# Check if one microorganism is to be displayed
		$view = $micros->num_rows==1;
		# Get page number
		$page = ceil(($start+1)/10);
		# Prepare URL variables
		$optstr = Tool::optstrify($opts); ?>
		
		<div id="side"> <?php
			# Show Back and Next buttons for navigation ?>
			<div id="navis"> <?php
				# Links to previous ten items ?>
				<a href="main.php?<?php echo $optstr.(empty($query) ? '' : '&q='.$query).(empty($start) ? '&s=0' : '&s='.(intval($start)-10)) ?>"
					class="navi ui ui-button prev <?php if(empty($start)) echo 'disabled' ?>" tabindex="-1" title="Previous 10 items"></a> <?php
				# Links to next ten items ?>
				<a href="main.php?<?php echo $optstr.(empty($start) ? '&s=10' : '&s='.(intval($start)+10)) ?>"
					class="navi ui ui-button next <?php if(($micros->num_rows<10) or ($micros->num_rows*$page)>=$size) { echo 'disabled'; } ?>" tabindex="-1" title="Next 10 items"></a>
			</div> <?php
			
			# Knobs to stage an microorganism ?>
			<div id="knobs"> <?php $i = 1;
				while($micro = $micros->fetch_object()) {
					# Contains data query name, id, tool (tooltip help)
					$name = Tool::truncate($trname = $micro->Name, 80); ?>
					<div id="knob<?php echo $micro->ID ?>" class="knob micro <?php if($view) echo "lock" ?>"
						data-id="<?php echo $micro->ID ?>" data-tool="{'head':'<b class=\'cool\'><?php echo $name ?></b>','x':'l'}">
						<?php echo $i++; ?>
					</div> <?php
				} ?>
			</div>
		</div> <?php
		
		# Labels stage items (header) ?>
		<div id="hnotif" class="escape"> <?php
			# Shows metadata of all searched items ?>
			<span id="query" class="escape iblock" data-tool="{'head':'<?php echo ($all = (empty($query) and empty($opts['q']))) ? "All microorganisms" : (empty($opts['q']) ? $trname : $opts['q']) ?>','x':'l'}"
				<?php if(!($nctrl = empty($_COOKIE['ctrl']['search']))) { echo 'style="width:400px"'; } ?>>
				<?php echo (isset($opts['rnk']) ? $this->taxalabel[$opts['rnk']].': ' : '')
					.($all ? "All microorganisms" : ((isset($opts['view']) or $view) ? $name : (empty($_REQUEST['htitle']) ? $query : $_REQUEST['htitle']))) ?>
			</span>
			
			<span>
				<span id="search-ctrls" <?php if($nctrl) { echo 'class="none"'; } ?>> <?php
					# No. of returned results
					echo '<span id="numresults">Showing '.($micros->num_rows).' of <b>'.$size.'</b> result(s)</span> on page ';
					
					# Many microorganisms are to be viewed
					$ob = isset($_REQUEST['ob']); $of = true;
					unset($opts['ob']); unset($opts['oa']);
					$optstr = Tool::optstrify($opts);
					
					# Prepare filter options and page selector ?>
					<select id="main-page" class="page navi" data-tool="{'head':'Page'}"> <?php
						for($i=0, $x=$size/10; $i<$x; $i++)	echo "<option ".((isset($opts['s']) and $opts['s']==($i*10)) ? 'selected="selected"' : '').'value="main.php?'.$optstr.(empty($query) ? '' : '&q='.$query).'&s='.($i*10).'">'.($i+1).'</option>';?>
					</select> sorted by <?php
					
					# Prepare filter options ?>
					<select class="navi" data-tool="{'head':'Sort'}">
						<option value="main.php?<?php echo $optstr ?>&ob=name&oa=asc" <?php if($ob and $_REQUEST['ob']=='name') { echo 'selected="selected"'; $of = false; } ?>>Name</option>
						<option value="main.php?<?php echo $optstr ?>&ob=code&oa=asc" <?php if($of and $ob and $_REQUEST['ob']=='code') { echo 'selected="selected"'; $of = false; } ?>>Code</option>
						<option value="main.php?<?php echo $optstr ?>&ob=notes&oa=asc" <?php if($of and $ob and $_REQUEST['ob']=='notes') { echo 'selected="selected"'; $of = false; } ?>>Notes</option>
						<option value="main.php?<?php echo $optstr ?>&ob=crtby&oa=asc" <?php if($of and $ob and $_REQUEST['ob']=='crtby') { echo 'selected="selected"'; $of = false; } ?>>Author</option>
						<option value="main.php?<?php echo $optstr ?>&ob=updon&oa=desc" <?php if($of and $ob and $_REQUEST['ob']=='updon') { echo 'selected="selected"'; $of = false; } ?>>Last edited</option>
						<option value="main.php?<?php echo $optstr ?>&ob=shron&oa=desc" <?php if($of and $ob and $_REQUEST['ob']=='shron') { echo 'selected="selected"'; $of = false; } ?>>Last shared</option>
						<option value="main.php?<?php echo $optstr ?>&ob=crton&oa=desc" <?php if($of and $ob and $_REQUEST['ob']=='crton') { echo 'selected="selected"'; $of = false; } ?>>Date created</option>
						<option value="main.php?<?php echo $optstr ?>&ob=id&oa=asc" <?php if($of and $ob and $_REQUEST['ob']=='id') { echo 'selected="selected"'; $of = false; } ?>>ID</option>
					</select>
				</span>
				<span <?php if(!$nctrl) { echo 'class="none"'; } ?>><?php echo "$micros->num_rows of <b>$size</b> result(s) on page <b>$page</b>";  ?></span> <button type="button" class="navi-details <?php echo (!$nctrl ? 'selected' : '') ?>" data-tool="{'head':'Search controls'}"></button>
			</span>
		</div> <?php
		
		# Contains all microorganism headers ?>
		<div id="stage"> <?php
			# Reset pointer to first row in mysql result
			$micros->data_seek(0);
			
			# List all microorganisms on its own entry page
			while($micro = $micros->fetch_object()) {
				# Show first the heading of each microorganism
				$this->displayHeading($micro, $view);
			} ?>
		</div> <?php
	} # function displayMain
	
	/**
	* Display a microorganism heading
	* Displays a heading for each microorganism in the results
	* which contains the microorganism's scientific name
	* 
	* @access public
	* @param mixed $micro Contains all details of the microorganism
	* @param boolean $cont Checks if content is to be displayed too
	*/
	public function displayHeading($micro, $cont) {
		# List a microorganism first as an area with a header that can be selected/clicked by the user in the stage
		# Data included: head (scientific name), id (microorganism id)
		?> <div id="area<?php echo $micro->ID ?>" class="stage area micro" data-head="<?php echo $micro->Name ?>">
			<div class="div-header micro <?php echo $cont ? "active lock" : "heading" ?>" data-id="<?php echo $micro->ID ?>" data-content="micro"
				<?php if(strlen($micro->Name)>100) echo 'data-tool="{\'head\':\''.$micro->Name.'\',\'x\':\'l\'}"' ?>>
				<i><a href="main.php?micro=view&id=<?php echo $micro->ID ?>" class="name" tabindex="-1">
					<?php echo $micro->Name ?></a></i> <span><?php echo $micro->Authors ?></span>
			</div> <?php
			
			# Show microorganism's contents if necessary
			if($cont) {
				$this->displayContent($micro, $cont);
			} ?>
		</div> <?php
	} # function displayHeading
	
	/**
	* Display taxonomy
	* Displays the taxonomic positions in the taxonomy browser
	* 
	* @access public
	* @param mixed $taxa Contains all taxonomic positions in results
	*/
	public function displayTaxa($taxa) {
		$positions = array('kng'=>'Kingdom', 'phy'=>'Phylum', 'cls'=>'Class', 'ord'=>'Order', 'fam'=>'Family', 'gen'=>'Genus', 'spc'=>'Species');
		$i = 0;
		
		# Iterate through each taxonomic rank
		foreach($positions as $key => $rnk) {
			# Taxonomic rank is set and must be displayed
			if(isset($taxa[$i]) and !empty($taxa[$i]->num_rows)) { ?><hr/>
				<label class="gray"><?php echo $rnk ?> (<? echo $taxa[$i]->num_rows ?>)</label>
				<ul> <?php
					# Iterate through each higher taxonomic ranks
					for($j=0, $taxa[$i]->data_seek(0); $taxon=$taxa[$i]->fetch_object(); $j++) { ?>
						<li data-tool="{'head':'<span class=\'small\'>
							<a href=\'main.php?micro=view&c=taxon&rnk=<?php echo $i ?>&q=<?php echo $taxon->Name ?>\' target=\'_blank\' title=\'Microorganisms belonging to <?php echo lcfirst($rnk).' '.$taxon->Name ?>\'>Search</a>
							<?php if($key!='spc') { ?>&#9642; <a class=\'view-taxon-in\' data-id=\'<?php echo $taxon->Name ?>\' data-taxon=\'<?php echo $i ?>\' title=\'<?php echo $rnk.' '.$taxon->Name ?> in taxonomy browser\'>Browse</a> <?php }
								# Check if taxon author or Prime user is using taxonomy browser; display edit taxon
								if($taxon->CrtBy==$this->user['id'] or $this->user['type']=='PRIME') { ?>
									&#9642; <a class=\'edit-taxon\' title=\'<?php echo $rnk.' '.$taxon->Name ?>\' data-id=\'<?php echo $taxon->ID ?>\' data-rank=\'<?php echo $i ?>\'>Edit</a>
									<span class=\'none\'> &#9642; <span class=\'cancel-edit-taxon\' title=\'Cancel\'>&#x2716;</span></span> <?php
								}
							?></span>','stay':'true','x':'l'}">
							<input class="taxon reqd read <?php if(in_array($key, array('gen','spc'))) { echo 'ital'; } ?>" name="taxon" readonly="readonly" type="text" value="<?php echo $taxon->Name ?>"/>
							<!--<input class="code reqd read" name="code" readonly="readonly" type="text" value="<?php echo $taxon->Code ?>"/>-->
						</li> <?php
					} ?>
				</ul> <?php
			} $i++;
		}
	} # function displayTaxa
	
	/**
	* Display contents of microorganism
	* Displays the contents of a microorganism, from its scientific name
	* to its associated items in other areas of the system
	* 
	* @access public
	* @param mixed $micro Contains all details of the microorganism
	* @param boolean $cont Checks if only one microorganism is found in results
	*/
	public function displayContent($micro, $cont) { ?>
		<div class="div-content">
			<form id="form-micro<?php echo $micro->ID ?>" class="micro" name="form-micro" method="post" action="process.php?micro=edit" enctype="multipart/form-data" novalidate="novalidate">
			<div class="div-upper">
				<div class="div-body"> <?php
					# Identity of microorganism ?>
					<div class="div-peel"><b>Identity</b></div>
					<div class="div-case"> <?php
						# Name of microorganism?>
						<label>Name:</label>
						<input name="name" class="reqd ital read" readonly="readonly" type="text" value="<?php echo $micro->Name ?>"/><br/> <?php
						
						$pref = !empty($micro->PrefID);
						
						# Preferred ID is not empty, display preferred microorganism
						if($pref) {
							# Search preferred microorganism ?>
							<label>Preferred:</label> <?php
							list($resPref, $sizePref) = $this->search($micro->PrefID, array('c'=>'id'), 0, null);
							
							# Preferred microorganism is found
							if(!empty($sizePref)) {
								$pmicro = $resPref->fetch_object();
								$pmicroName = $pmicro->Name.' '.$pmicro->Authors; ?>
								
								<textarea name="prefID[val]" class="abled ital read skip" readonly="readonly" rows="<?php echo ceil(strlen($pmicroName)/100) ?>" data-guess="micro=guess"
									data-tool="{'head':'<span class=\'permalink\'><a href=\'main.php?micro=view&id=<?php echo $pmicro->ID ?>\' target=\'_blank\'><?php echo $pmicro->Name ?></a></span>','stay':1,'x':'l'}">
									<?php echo $pmicroName ?></textarea><br/> <?php
							}
							else {
								# Preferred microorganism is not found ?>
								<input name="prefID[val]" class="abled read ital skip" readonly="readonly" data-guess="micro=guess" type="text"/><br/> <?php
							}
							
							# Preferred microorganism's ID ?>
							<input name="prefID[id]" class="abled" type="hidden"/> <?php
						}
						
						# Scientific authors ?>
						<label>Authors:</label>
						<textarea name="author" class="read abled" readonly="readonly" <?php if(empty($micro->Authors)) { ?> rows="1"> <?php } else { ?> rows="<?php echo ceil(strlen($micro->Authors)/100); ?>"><?php echo $micro->Authors; } ?></textarea>
						
						<div class="pref none">
							<select name="pref" style="width:88px">
								<option value="1" <?php if($micro->Pref=='1') { echo 'selected="selected"'; } ?>>Preferred</option>
								<option value="0" <?php if($micro->Pref=='0') { echo 'selected="selected"'; } ?>>Synonym</option>
							</select>
							<span class="<?php echo $micro->Pref=='1' ? 'hide' : '' ?>">
								<input name="prefID[name]" type="text" placeholder="Preferred name (optional)" class="ital" data-guess="micro=guess" style="width:408px"/>
								<input name="prefID[id]" type="hidden" class="abled"/>
							</span>
						</div>
					</div> <?php
					
					# Taxonomic position # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # 
					$taxon = $this->retrieve('taxon', null, $micro, '', ''); ?>
					
					<div class="div-peel peel next open <?php echo ($empty = empty($taxon)) ? 'on' : 'off' ?>"><b>Taxonomy</b></div>
					<div class="div-case <?php if($empty) echo 'none' ?>"><ul> <?php $i = 0;
						# Iterate through each ranks to display them
						foreach($this->ranks as $key => $rnk) { ?>
							<li class="taxon" style="padding-left:<?php //echo ($i+1)*30 ?>25px"> <?php
								# Rank at that point is not empty and must be displayed (Taxon name, Code, ID)
								if(!empty($taxon[$rnk])) { ?>
									<input name="taxon[<?php echo $rnk ?>][name]" value="<?php echo $taxon[$rnk]->Name ?>" class="taxon read abled <?php if(in_array($rnk, array('genus','species'))) { echo 'ital'; } ?>" readonly="readonly" type="text" placeholder="<?php echo ucfirst($rnk) ?>" data-guess="micro=guess&a=taxong&i=<?php echo $i ?>"
										data-tool="{'head':'<b><?php echo ucfirst($rnk) ?></b>&nbsp;<span class=\'small\'>
											<a href=\'main.php?micro=view&c=taxon&rnk=<?php echo $i ?>&q=<?php echo $taxon[$rnk]->Name ?>\' target=\'_blank\' title=\'Microorganisms belonging to <?php echo $rnk.' '.$taxon[$rnk]->Name ?>\'>Search</a> &#9642;
											<a class=\'view-taxon\' data-id=\'<?php echo $taxon[$rnk]->ID ?>\' data-taxon=\'<?php echo $i ?>\' title=\'<?php echo ucfirst($rnk).' '.$taxon[$rnk]->Name ?> in taxonomy browser\'>Browse</a>
										</span>','stay':'true','x':'l'}"/>
									<!--<input name="taxon[<?php echo $rnk ?>][code]" value="<?php echo $taxon[$rnk]->Code ?>" class="code read abled" placeholder="Code" readonly="readonly" type="text" data-tool="{'head':'Code','x':'l'}"/>-->
									<input name="taxon[<?php echo $rnk ?>][id]" value="<?php echo $taxon[$rnk]->ID ?>" type="hidden" class="abled"/> <?php
								}
								else {
									# Taxon rank is empty, display input fields ?>
									<input name="taxon[<?php echo $rnk ?>][name]" class="taxon read abled skip" readonly="readonly" type="text" data-guess="micro=guess&a=taxong&i=<?php echo $i ?>" placeholder="<?php echo ucfirst($rnk) ?>" data-tool="{'head':'<b><?php echo ucfirst($rnk) ?></b>','x':'l'}"/>
									<!--<input name="taxon[<?php echo $rnk ?>][code]" placeholder="Code" class="code read abled" readonly="readonly" type="text" data-tool="{'head':'Code','x':'l'}"/>-->
									<input name="taxon[<?php echo $rnk ?>][id]" type="hidden" class="abled"/> <?php
								} ?>
							</li> <?php $i++;
						} ?></ul>
					</div> <?php
					
					# Other names # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # 
					# Retrieve all associsated synonyms and common names
					list($resSyno, $sizeSyno) = $this->retrieve('syno', $micro->ID, null, '', '');
					list($resComn, $sizeComn) = $this->retrieve('comn', $micro->ID, null, '', ''); ?>
					
					<div class="div-peel peel <?php echo ($empty = (empty($sizeSyno) and empty($sizeComn))) ? "on" : "off open" ?> next">
						<b>Names</b> <span><?php echo $sizeNames = $sizeSyno + $sizeComn ?></span>
					</div>
					<div class="div-case <?php if($empty) echo "none" ?>">
						<label>Synonyms:</label> <?php
						if(!$empty) { ?>
							<ol> <?php
								while($syno = $resSyno->fetch_object()) { ?>
									<li class="syno">
										<a href="main.php?micro=view&id=<?php echo $syno->ID ?>"><?php echo '<i>'.$syno->Name.'</i>' ?></a> <span class="dim"><?php echo $syno->Authors ?></span>
										<button type="button" class="remove icon read" data-area="syno" data-id="<?php echo $syno->CID ?>"></button>
									</li> <?php
								} ?>
							</ol> <?php
						}
						else {
							echo "0<br/>";
						} ?>
						
						<div class="none">
							<div class="default">
								<input name="syno[name][]" type="text" placeholder="Synonym" class="syno abled target" data-guess="micro=guess"/>
								<button class="append icon" type="button" data-area="micro" data-id="0"></button>
								<input name="syno[id][]" type="hidden" class="abled"/><br/>
								<a class="addmore peel on next vanish">Authors</a>
								<div class="none"><input name="syno[auth][]" type="text" placeholder="Author/s" class="abled"/></div>
							</div>
							<div class="synos"></div>
						</div>
						<button type="button" class="addmore peel on prev read" data-on="Add" data-off="Cancel">Add</button><hr/>
						
						<label>Common names:</label> <?php
						if(!$empty) { ?>
							<ol> <?php
								while($comn = $resComn->fetch_object()) { ?>
									<li class="comn">
										<span><?php echo $comn->Name ?></span> <button type="button" class="remove icon read" data-area="comn" data-id="<?php echo $comn->CID ?>"></button>
									</li> <?php
								} ?>
							</ol> <?php
						}
						else {
							echo "0<br/>";
						} ?>
						
						<div class="none">
							<div class="default">
								<input name="comn[name][]" type="text" placeholder="Common name" class="comn abled target"/>
								<button class="append icon" type="button" data-area="micro" data-id="0"></button>
								<input name="comn[id][]" type="hidden" class="abled"/><br/>
								<a class="addmore peel on next vanish small">Language</a>
								<div class="none"><input name="comn[lang][]" type="text" placeholder="Language" class="abled"/></div>
							</div>
							<div class="comns"></div>
						</div>
						<button type="button" class="addmore peel on prev read" data-on="Add" data-off="Cancel">Add</button>
					</div> <?php
					
					# Hosts # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # 
					list($resHost, $sizeHost) = $this->retrieve('host', $micro->ID, null, '', ''); ?>
					
					<div class="div-peel peel <?php echo ($empty = empty($sizeHost)) ? "on" : "off open" ?> next">
						<b>Hosts</b> <span><?php echo $sizeHost ?></span>
					</div>
					<div class="div-case <?php if($empty) echo "none" ?>"> <?php
						if(!$empty) { ?>
							<ol> <?php
								while($host = $resHost->fetch_object()) { ?>
									<li class="host" data-tool="{'head':'<?php echo $host->Code ?>','x':'l'}">
										<span class="ital"><?php echo $host->Name ?></span> <span class="dim"><?php echo $host->Authors ?></span>
										<button type="button" class="remove icon read" data-area="host" data-id="<?php echo $host->CID ?>"></button>
									</li> <?php
								} ?>
							</ol> <?php
						} ?>
						
						<div class="none">
							<div class="default">
								<input name="host[name][]" class="host abled target" type="text" placeholder="Scientific name" data-guess="micro=guess&a=host" style="width:408px"/>
								<input name="host[code][]" class="code abled" type="text" placeholder="Code"/>
									<button class="append icon" type="button" data-area="micro" data-id="0">
									<input name="host[id][]" type="hidden" class="abled"/></button>
								<a class="addmore peel on next vanish small">Authors, Common names</a>
								<div class="none">
									<input name="host[auth][]" class="abled" placeholder="Authors" type="text" data-tool="{'head':'Separated by <b>semi-colon (;)</b>','x':'r'}"/><br/>
									<input name="host[comn][]" class="abled" placeholder="Common names" type="text" data-tool="{'head':'Separated by <b>semi-colon (;)</b>','x':'r'}"/>
								</div>
							</div>
							<div class="comns"></div>
						</div>
						<button type="button" class="addmore peel on prev read" data-on="Add" data-off="Cancel">Add</button>
					</div> <?php
					
					# Locations # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # 
					list($resLoc, $sizeLoc) = $this->retrieve('loc', $micro->ID, null, '', 'LIMIT 10'); ?>
					
					<div class="div-peel peel <?php echo ($empty = empty($sizeLoc)) ? "on" : "off open" ?> next">
						<b>Locations</b> <span><?php echo $sizeLoc ?></span>
					</div>
					<div class="div-case <?php if($empty) echo "none" ?>"> <?php
						if(!$empty) { ?>
							<ol> <?php
								while($loc = $resLoc->fetch_object()) { ?>
									<li class="loc">
										<a href="main.php?loc=view&id=<?php echo $loc->ID ?>"><?php echo $loc->Name ?></a>
										<button type="button" class="remove icon read" data-area="loc" data-id="<?php echo $loc->ID ?>"></button><br/>
									</li> <?php
								} ?>
							</ol>
							<a class="fetch loc tick" data-area="micro" data-id="<?php echo $micro->ID ?>" data-start="10">Show more</a> <?php
						} ?>
						
						<div class="none">
							<div class="default">
								<input type="text" class="loc" name="loc[val][]" placeholder="Location name" data-guess="loc=guess"/>
								<button class="append icon" type="button" data-area="loc" data-id="0"></button>
								<input type="hidden" name="loc[id][]" class="abled"/>
							</div>
							<div class="locs"></div>
						</div>
						<button type="button" class="addmore peel on prev read" data-on="Add" data-off="Cancel">Add</button>
					</div>
					
					<div class="div-peel peel <?php echo ($empty = (empty($micro->Notes) or $micro->Notes=='NULL')) ? "on" : "off open" ?> next notes">
						<b>Notes</b></div>
					<div class="div-case <?php if($empty) echo "none" ?>">
						<textarea name="notes" rows="<?php echo $empty ? '5' : ceil(strlen($micro->Notes)/100) ?>" class="read abled" readonly="readonly"> <?php
							echo $micro->Notes ?></textarea>
					</div>
					
					<div class="div-peel peel <?php echo ($empty = (empty($micro->Ref) or $micro->Ref=='NULL')) ? "on" : "off open" ?> next ref">
						<b>References</b></div>
					<div class="div-case <?php if($empty) echo "none" ?>">
						<textarea name="ref" rows="<?php echo $empty ? '3' : ceil(strlen($micro->Ref)/100) ?>" class="read abled" readonly="readonly"> <?php
							echo $micro->Ref ?></textarea>
					</div> <?php
					
					# Images # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # 
					list($resImg, $sizeImg) = $this->retrieve('img', $micro->ID, null, '', 'LIMIT 10'); ?>
					
					<div class="div-peel peel <?php echo ($empty = empty($sizeImg)) ? "on" : "off open" ?> next img">
						<b>Images</b> <span><?php echo $sizeImg ?></span>
					</div>
					<div class="div-case imgs <?php if($empty) echo "none" ?>"> <?php
						if(!empty($sizeImg)) {
							while($img = $resImg->fetch_object()) { ?>
								<span class="img">
									<a href="main.php?img=view&id=<?php echo $img->ID ?>">
									<img class="stage file locked ghost" src="<?php echo empty($img->Thumb) ? 'template/img.jpg' : $img->Thumb ?>" alt="<?php echo $img->Title ?>" style="width:<?php echo (125/$img->Height)*$img->Width ?>px"
										data-id="<?php echo $img->ID ?>" data-src="<?php echo $img->Path ?>" data-visib="<?php echo $img->Visib ?>" data-categ="<?php echo $img->Categ ?>"
										data-tool="{'head':'<span class=\'permalink\'><a href=\'main.php?img=view&id=<?php echo $img->ID ?>\' target=\'_blank\'><?php echo $img->Title ?></a></span>','stay':'true','x':'l'}"/></a>
									<div class="ctrl-img none">
										<div class="ctrl-main">
											<input name="pic" class="def-img abled" type="checkbox" value="<?php echo $img->Thumb ?>" id="pic<?php echo $img->ID ?>"/> <label for="pic<?php echo $img->ID ?>">Default</label>
											<input name="rimg[]" class="rmv-img abled" type="checkbox" value="<?php echo $img->ID ?>" data-area="micro" id="rimg<?php echo $img->ID ?>"/> <label for="rimg<?php echo $img->ID ?>">Remove</label>
										</div>
									</div>
								</span> <?php
							} ?> <span class="imgs"></span>
							
							<a class="fetch img tick" data-area="micro" data-id="<?php echo $micro->ID ?>" data-start="10">Show more</a> <?php
						} ?>
						
						<div class="none">
							<span class="default">
								<input name="img[val][]" class="img" type="text" placeholder="Image title" data-guess="img=guess"/>
								<button class="append icon" type="button" data-area="img" data-id="0"></button><br/>
								<input name="img[id][]" type="hidden" class="abled">
							</span>
							<div class="imgs"></div>
						</div>
						<button type="button" class="addmore peel on prev read" data-on="Add" data-off="Cancel">Add</button>
					</div> <?php
					
					# Marks # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # 
					list($resMark, $sizeMark) = $this->retrieve('mark', $micro->ID, null, '', 'LIMIT 10'); ?>
					
					<div class="div-peel peel <?php echo ($empty = empty($sizeMark)) ? "on" : "off open" ?> next img">
						<b>Marks</b> <span><?php echo $sizeMark ?></span>
					</div>
					<div class="div-case <?php if($empty) echo "none" ?>"> <?php
						if(!empty($sizeMark)) {
							while($mark = $resMark->fetch_object()) { ?>
								<span class="img">
									<a href="main.php?img=view&id=<?php echo $mark->ID ?>">
										<img class="stage file locked ghost" src="<?php echo empty($mark->Thumb) ? 'template/img.jpg' : $mark->Thumb ?>" alt="<?php echo $mark->Title ?>"
											data-id="<?php echo $mark->ID ?>" data-src="<?php echo $mark->Path ?>" data-visib="<?php echo $mark->Visib ?>" data-categ="<?php echo $mark->Categ ?>" style="width:<?php echo (125/$mark->Height)*$mark->Width ?>px"
											data-tool="{'head':'<span class=\'permalink\'><a href=\'main.php?img=view&id=<?php echo $mark->ID ?>\' target=\'_blank\'><?php echo $mark->Title ?></a></span>','x':'l','stay':1}"/></a>
									<div class="ctrl-img none">
										<div class="ctrl-main">
											<input name="pic" class="def-img abled" type="checkbox" value="<?php echo $mark->Thumb ?>" id="pic<?php echo $mark->ID ?>"/> <label for="pic<?php echo $mark->ID ?>">Default</label>
											<input name="rmimg[]" class="rmv-img abled" type="checkbox" value="<?php echo $mark->ID ?>" data-area="micro" id="rmimg<?php echo $mark->ID ?>"/> <label for="rmimg<?php echo $mark->ID ?>">Remove</label>
										</div>
									</div>
								</span> <?php
							} ?> <span class="marks"></span>
							
							<a class="fetch rsrc tick" data-area="micro" data-id="<?php echo $micro->ID ?>" data-start="10">Show more</a> <?php
						} ?>
					</div> <?php
					
					# Projects as Documents # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # 
					list($resProj, $sizeProj) = $this->retrieve('proj', $micro->ID, null, '', 'LIMIT 10'); ?>
					
					<div class="div-peel peel <?php echo ($empty = empty($sizeProj)) ? "on" : "off open" ?> next proj">
						<b>Documents</b> <span><?php echo $sizeProj ?></span>
					</div>
					<div class="div-case <?php if($empty) echo "none" ?>"> <?php
						if(!$empty) { ?>
							<ol> <?php
								while($proj = $resProj->fetch_object()) { ?>
									<li class="proj">
										<a data-title="<?php echo $proj->Title ?>" data-doc="<?php
											if(!empty($proj->DocID)) {
												$sel = "SELECT Path FROM Documents WHERE ID='{$proj->DocID}'";
												$res = $this->mysqli->query($sel);
												
												if($res and $res->num_rows > 0) {
													$doc = $res->fetch_object();
													echo $doc->Path;
												}
											}
										?>" href="main.php?proj=view&id=<?php echo $proj->ID ?>" title="<?php echo $proj->Title ?>"><?php echo $proj->Ref ?></a>
									</li> <?php
								} ?>
							</ol>
							
							<a class="fetch proj tick" data-area="micro" data-id="<?php echo $micro->ID ?>" data-start="10">Show more</a>  <?php
						} ?>
					</div> <?php
					
					# Resources # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # 
					list($resRsrc, $sizeRsrc) = $this->retrieve('rsrc', $micro->ID, null, '', 'LIMIT 10'); ?>
					
					<div class="div-peel peel <?php echo ($empty = empty($sizeRsrc)) ? "on" : "off open" ?> next rsrc">
						<b>Resources</b> <span><?php echo $sizeRsrc ?></span>
					</div>
					<div class="div-case <?php if($empty) echo "none" ?>"> <?php
						if(!$empty) { ?>
							<ol> <?php
								while($rsrc = $resRsrc->fetch_object()) { ?>
									<li class="rsrc">
										<a href="main.php?rsrc=view&id=<?php echo $rsrc->ID ?>"><?php echo $rsrc->Title ?></a>
										<button type="button" class="remove icon read" data-area="rsrc" data-id="<?php echo $rsrc->ID ?>"></button><br/>
									</li> <?php
								} ?>
							</ol>
							
							<a class="fetch rsrc tick" data-area="micro" data-id="<?php echo $micro->ID ?>" data-start="10">Show more</a> <?php
						} ?>
						
						<div class="none">
							<div class="default">
								<input type="text" class="rsrc" name="rsrc[val][]" placeholder="Resource title" data-guess="rsrc=guess"/>
								<button class="append icon" type="button" data-area="rsrc" data-id="0"></button>
								<input type="hidden" name="rsrc[id][]" class="abled"/>
							</div>
							<div class="rsrcs"></div>
						</div>
						<button type="button" class="addmore peel on prev read" data-on="Add" data-off="Cancel">Add</button>
					</div> <?php
					
					# Files # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #  ?>
					<div class="div-peel peel on next file none"><b>Files</b></div>
					<div class="div-case file none">
						<input name="file[]" type="file" class="file" multiple="multiple" accept="image/jpeg,image/gif,application/pdf"/>
					</div> <?php
					
					# Input # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # ?>
					<div class="div-peel peel on next file none"><b>Update</b></div>
					<div class="div-case file none">
						<input name="input[]" type="file" class="file" accept="application/json"/>
					</div> <?php
					
					# Settings # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # ?>
					<div class="div-peel peel on next safe none"><b>Settings</b> <span class="setting help"></span></div>
					<div class="div-case none safe"></div>
				</div> <?php
				
				# Side header # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # ?>
				
				<div class="div-head">
					<img class="img file default ghost" src="<?php echo empty($micro->ImgPath) ? (empty($imgPath) ? "template/micro.jpg" : $imgPath) : $micro->ImgPath ?>" alt="<?php echo $micro->Name ?>"/>
					
					<div class="controls"> <?php
						if(!isset($_GET['map'])) { ?>
							<button class="distn dial" data-area="micro" data-id="<?php echo $micro->ID ?>" type="button"><span>Distribution</span></button><hr/> <?php
						} ?>
						
						<button class="share dial" data-area="micro" data-id="<?php echo $micro->ID ?>" type="button"><span>Share</span></button> <?php
						
						$sett = new Setting('micro', null, $this->mysqli, $this->user);
						$verified = $sett->verify($micro->ID) and in_array($this->user['type'], array('PRIME','ADMIN'));
						
						if($micro->Categ=='BSC' or $verified) { ?>
							<a href="process.php?micro=get&id=<?php echo $micro->ID ?>"><span class="dload dial button"><span>Download</span></span></a> <?php
						} ?><hr/>
						
						<button class="details dial" type="button" data-area="micro" data-id="<?php echo $micro->ID ?>" data-name="<?php echo $micro->Name ?>"><span>Details</span></button>
						
						<button class="stat dial peel on next" type="button"><b>Contents</b></button>
						<ul class="metas none"> <?php
							if($pref) { ?>
								<li class="meta">Names <span><?php echo $sizeNames+1 ?></span></li> <?php
							} ?>
							<li class="meta">Images <span><?php echo $sizeImg ?></span></li>
							<li class="meta">Marks <span><?php echo $sizeMark ?></span></li>
							<li class="meta">Locations <span><?php echo $sizeLoc ?></span></li>
							<li class="meta">Resources <span><?php echo $sizeRsrc ?></span></li>
							<li class="meta">Projects <span><?php echo $sizeProj ?></span></li>
						</ul> <?php
						
						if($verified) { ?><hr/>
							<button class="edit dial" data-area="micro" data-id="<?php echo $micro->ID ?>" type="reset"><span>Edit</span></button> <?php
						} ?>
					</div>
				</div>
				
				<div class="div-mind">
					<input name="id" type="hidden" class="id abled" value="<?php echo $micro->ID ?>"/>
					<input name="upd" type="checkbox" class="abled" value="<?php echo $micro->ID ?>"/>
					<input name="del" type="checkbox" class="del abled" value="<?php echo $micro->ID ?>"/>
					<input name="recov" type="checkbox" class="recov abled" value="<?php echo $micro->ID ?>"/>
				</div>
			</div> <?php
			
			# Dial # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # ?>
			
			<div class="div-dial"> <?php
				if($micro->Remove=='0') { ?>
					<button class="delete tick read left" type="button" form="form-micro<?php echo $micro->ID ?>" data-area="micro">Delete</button> <?php
				}
				else { ?>
					<button class="recover tick read left" type="button" form="form-micro<?php echo $micro->ID ?>" data-area="micro">Recover</button> <?php
				} ?>
				<button type="button" form="form-micro<?php echo $micro->ID ?>" class="cancel edit read">Cancel</button>
				<button type="submit" class="read">Update</button> <?php
				
				if(!$cont) { ?>
					<button type="button" class="close-content reset">Close</button> <?php
				} ?>
			</div>
			</form>
		</div> <?php
	}
} # function displayContent
?>
